if

goto

The goto keyword causes program execution to jump to the label specified in the goto statement. The general form of goto is

 goto label; . . . label:

All labels must end in a colon and must not conflict with keywords or function names. Furthermore, a goto can branch only within the current function—not from one function to another.

Programming Tip 

Although the goto fell out of favor decades ago as a preferred method of program control, it does occasionally have its uses. One of them is as a means of exiting from a deeply nested routine. For example, consider this fragment:

int i, j, k; int stop = 0; for(i=0; i<100 && !stop; i++) {   for(j=0; j<10 && !stop; j++) {     for(k=0; k<20; k++) {       // ...       if(something()) {         stop = 1;         break;       }     }   } }

As you can see, the variable stop is used to cancel the two outer loops if some program event occurs. However, a better way to accomplish this is shown below, using a goto:

int i, j, k; for(i=0; i<100; i++) {   for(j=0; j<10; j++) {     for(k=0; k<20; k++) {       // ...       if(k+4 == j + i) {         goto done;       }     }   } } done: // ...

As you can see, the use of the goto eliminates the extra overhead that was added by the repeated testing of stop in the previous version.

Although the goto as a general-purpose form of loop control should be avoided, it can occasionally be employed with great success.




C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net