A way to replace Goto statement

Source: Internet
Author: User
Tags goto

When the error occurs, the function needs to return, using the goto statement to jump to the end, and then perform the corresponding release of resources, is a common way of writing, which is also the use of the GOTO statement more reasonable scheme. Through several projects, most of these programmes have been adopted.

But this has a negative effect, because all the variable definitions must be preceded by Goto, so you have to place all the variable definitions in the function's head, and the actual scope of the variable may be only a few adjacent lines, so the readability becomes weaker.

The following example uses Do{}while (0) and jumps to use the break method. Can solve this problem very well. You can define variables and use them wherever possible in a code snippet.

The source of this idea, I have not been able to remember in addition, should be seen in a book, marked, to be verified in the future.

#include <cstdio>
int main ()
{
do{
	int a =;
	if (a <)
	{break
		;
	} else
	{
		//to do something
	}
}while (0);

	To does something return 
	0;
}

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.