The goto Statement

Summary: The goto statement jumps from one part of the function to another.

Similar to the GOTO statement in Basic, goto in C performs an unconditional jump from one part of a function to any other part. The target of the goto statement is a label which you supply. The label must end with a colon, as do case labels, which we discussed earlier.

Most C programmers avoid using the goto statement. It's a bit inconsistent with the overall philosophy of C, which encourages structured, modular programming. And, regardless of philosophy, it can be very difficult to read and debug a program that is littered with haphazard unconditional jumps.

Nevertheless, goto has at least one sensible use. If a serious error occurs deep within a nested series of loops or conditional statements, goto offers the simplest escape. The following code has several levels of nesting, with a goto statement at the innermost level. If the value of error_count exceeds 15, the goto statement executes, transferring control to the label bail_out.

if( a == 1 )

{

while( b == 2 )

{

for( c = 0; c < 3; c = c + 1 )

{

if( d == 4 )

{

while( e == 6 )

{

if( error_count > 15 )

goto bail_out;

}

}

}

}

}

bail_out: /* The goto statement transfers control here. */

To achieve the same effect without goto, you'd have to add extra conditional tests to this code, making the code more complex and perhaps less efficient.

Names in goto labels are governed by the rules for variable names, which we'll discuss in the next two chapters. For now, just remember that a goto label is visible only in the function in which it appears. You can't execute a goto statement to jump from one function to another function.

The next two chapters explain how to create and manipulate data—variables and constants—in C programs. Chapter 4, “Data Types,” describes the basics, such as how to declare and initialize variables of different types. Chapter 5, “Advanced Data Types,” describes more advanced topics, such as the visibility of variables.