Labelled Statements

A labelled statement is any statement that is preceded by a label. A label is an identifier followed by a colon, ':'. A label is used to identify which statement is the target of a goto statement - that is, it marks which statement will be executed after the goto statement. A label may be before or after the goto statement. The colon does NOT appear in the goto statement which refers to it.

In the following program fragment:

	inf_loop_top:
	printf("On a clear day you can loop for ever.\n");
	goto inf_loop_top;

what is called an infinite loop has been created, i.e. one which will not terminate.

Lexically, the label precedes the printf() even though they are on different lines. They could have as well been placed on the same line:

	inf_loop_top: printf("On a clear day you can loop for ever.\n");
	goto inf_loop_top;

Putting the label on a separate line can make it a little easier to see, at the expense of the extra line. There can also be a labelled null statement as in:

	here: ;

If the above example had been longer, many pages rather than 3 lines, then it would have been much harder to recognize that it was an infinite loop. Further, the code comprising the loop could have been in several disjoint sections with more than one goto statement and with goto's going forward backward, into any tangle. It is for this reason, among others, that the goto statement is to be avoided as much as possible. It is better to use the other control flow statements when possible.

A label and any goto statements which refer to it must be in the same function. It is not possible to have a goto refer to a label in another function. The compiler will only look for labels within the the same function as the goto statement. Note that in 'C', labels are not declared as must be all other identifiers (e.g. data, functions, and tags).

It is suggested that each label identifier be not just a unique name for a given function, but be a meaningful word or phrase (intervening spaces of course not allowed) so as to help document the program.

Note that the 'name' space for labels is treated differently than all other identifiers in the sense that the exact same identifier (e.g. "sort") could be used as a label and also as either a variable or function name (but not both as a variable or function name) and as a struct or union tag.


© 1991-2008 Prem Sobel. All Rights Reserved.