Are C labels instructions or constants

63 Views Asked by At

I'm asking how are labels managed by C.

EX:

if (false)
label: printf("HELLO ");

printf("WORLD ");
goto label;

Prints WORLD HELLO on GCC is it undefined behavior? (the label definition isn't handled as an instruction by the compiler)

Otherweise I'd expect some kind of error like "encountered undefined label"

1

There are 1 best solutions below

0
dbush On

Labels are neither instructions or constants. They are there own construct. However, a label can only be applied to a statement.

The syntax for a labled statement is specified in section 6.8.1p1 of the C standard as follows:

labeled-statement:

  • identifier : statement
  • case constant-expression : statement
  • default : statement

In the above, the "identifier" in the first case is a named label. Labels have their own namespace separate from struct/union tags, members, or other identifiers. Labels also have function scope, meaning they can be used anywhere in the function where they are defined.

So your example (as well as the ones you deleted) are all valid because labels have function scope.