Tuesday, April 5, 2011

Horrors! goto's and labels in C

Horrors! goto's and labels

C has a goto statement and labels, so you can branch about the way you used to.  But most of the time goto's aren't needed.  (How many have we used up to this point?)  The code can almost always be more clearly expressed by for/while, if/else, and compound statements.
One use of goto's with some legitimacy is in a program which contains a long loop, where a while  would be too extended.  Then you might write
mainloop:
               ...
               goto mainloop;
Another use is to implement a break out of more than one level of for or while goto's can only branch to labels within the same function.there are a few situations where gotos may find a placeThe most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop.

Thus:

       for ( ... )
           for ( ... ) {
               ...
               if (disaster)
                   goto error;
           }
       ...
   error:
       /* clean up the mess */

This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.

A label has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the goto. The scope of a label is the entire function.

As another example, consider the problem of determining whether two arrays a and b have an element in common. One possibility is

       for (i = 0; i < n; i++)
           for (j = 0; j < m; j++)
               if (a[i] == b[j])
                   goto found;
       /* didn't find any common element */
       ...
   found:
       /* got one: a[i] == b[j] */
       ...

Code involving a goto can always be written without one, though perhaps at the price of some repeated tests or an extra variable. For example, the array search becomes

   found = 0;
   for (i = 0; i < n && !found; i++)
       for (j = 0; j < m && !found; j++)
           if (a[i] == b[j])
               found = 1;
   if (found)
       /* got one: a[i-1] == b[j-1] */
       ...
   else
       /* didn't find any common element */
       ...

With a few exceptions like those cited here, code that relies on goto statements is generally harder to understand and to maintain than code without gotos. Although we are not dogmatic about the matter, it does seem that goto statements should be used rarely, if at all. 


0 comments:

Post a Comment

Breaking News
Loading...
Quick Message
Press Esc to close
Copyright © 2013 Crack o Hack & tweak STORE All Right Reserved