development

goto vs return statement: C programming

It is a classic conflict of opinion when comes to choosing between goto and return.

I feel that goto is treated unfairly, biased, and unjustly. Why people are so paranoid about avoiding goto, is beyond my comprehension.

Let me explain my point with following example:

void foo()
{
if{...}
if{...}
if{...}
if{...}
if{...}
if{...}
if{...}
if{...}
}

Now if I populate the body of “if” with “return”; it is perfectly okay. It creates problems in later point of time.

Now, say you allocate a resource in foo(), where would you free it?

Going with “return” makes you free the resource in all “if” conditions that follow the place where you have allocated the resource.

Now, solve this problem with goto. All “if” should goto a single label, which would be placed at the end of the foo().

So, the clean-up work can now be placed under this label. This is much better than “return” statements:

– Code is more extensible. You may add more “if” conditions, without any fear of resource leaks.

– Avoids code duplication

– Even if the current function do not need “goto”, I propose to use “goto” for future extensibility.

Advertisements

Categories: development

Tagged as: ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.