If I jump into a block like in this example, jumping "over" the declarations,
#include <stdio.h>
int main(int argc, char *argv[]){
int counter = 0;
goto jump;
{
static int st = -9;
int au = -9;
jump:
printf("st = %d\n", st);
printf("au = %d\n", au);
au++;
st++;
counter++;
}
if(counter < 10) goto jump;
return 0;
}
I can compile it with gcc --std=c89 -pedantic
.
It seems that you can't really jump "over" declarations: the variables are still declared, even if the lines in which those declarations are made are never reached.
But somehow you can jump over definitions...
st
as a static variable gets initialized with the value -9 and counts up to 0.au
gets initialized with the value 0 and counts up to 9.Is 1. and/or 2. a behavior which is necessitated by the C standard?
In C static variables such as st
are initialized at program startup before main()
is called, even for static variables that are scoped to a function or block. Jumping past the declaration/initializer does not affect this, so for this particular scenario, no undefined, unspecified, or indeterminate behavior occurs.
For an automatic variable, such as au
, the initialization occurs when the declaration is reached in the execution of the block. Since the goto
jumps past that part of the block's execution, the value of au
remains indeterminate, and it is undefined behavior to use the variable's value in that situation without first setting it to some determinate value.
Note that several details of this are different in C++. For example, the C++ standard says that a program is ill-formed if it jumps past a declaration unless that declaration is for a POD type and the declaration does not contain an initializer.