Using Labels with the goto Statement

The appearance of an identifier label in the source program declares a label. Only a goto statement can transfer control to an identifier label. The following code fragment illustrates use of the goto statement and an identifier label to escape a tightly nested loop:

for( p = 0; p < NUM_PATHS; ++p )

{

NumFiles = FillArray( pFileArray, pszFNames )

for( i = 0; i < NumFiles; ++i )

{

if( (pFileArray[i] = fopen( pszFNames[i], "r" )) == NULL )

goto FileOpenError;

// Process the files that were opened.

}

}

FileOpenError:

cerr << "Fatal file open error. Processing interrupted.\n" );

In the above example, the goto statement transfers control directly to the statement that prints an error message if an unknown file-open error occurs.

The label has function scope and cannot be redeclared within the function. However, the same name can be used as a label in different functions.