The awkward goto statement

Source: Internet
Author: User

Previously seen effect xxx and other books, there will always be this one: avoid using goto statements

The reason is very simple, you a piece of code will jump here, a jump there, jump to the dizzy, like in the maze

It seems to make sense, but in practical use, it's not likely that anyone will jump.

In some cases, Goto is a more elegant way. Like what:

1. Multiple loops

Jump out of the loop with a break, if you jump out of multiple loops. This example is not uncommon, and everyone has their own way of coping: flag variables.

But if you use Goto, it will be more direct and easier to read.

In Java, it makes sense to allow Goto to be used only in this case.

2. Resource Recovery

In my opinion, this situation is more typical than the multiple loops.

Suppose a very common scenario: you initialize a bunch of modules at the beginning of the function and malloc a lot of memory, and you need to release them at the end of the function.

However, there are many steps in the function process that stop execution and exit at one step of failure.

At this time if direct return, to write a lot of release before return statements, there are n steps have n return, release statements to write n times, this is a nightmare.

In my opinion, the most elegant way is to do at the end of the function to do an exit flag, followed by the release of the statement, which step if the execution fails, directly goto exit, simple and understandable

In my opinion, there is no bad grammar, only bad programmers. Now advocating the use of some of the grammar, is not absolute, but said that a lot of people have fallen in here, if you do not have the full grasp, or try not to use, lest later into the quagmire of debug

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.