(Sorry for bad English.)
Question 1.
void foo(void)
{
goto inside;
for (;;) {
int stack_var = 42;
inside:
...
}
}
Will be a place in stack allocated for the stack_var when I goto the inside label? I.e. can I correctly use the stack_var variable within ...?
Question 2.
void foo(void)
{
for (;;) {
int stack_var = 42;
...
goto outside;
}
outside:
...
}
Will be a place in stack of the stack_var deallocated when I goto the outside label? E.g. is it correct to do return within ...?
In other words, is goto smart for correct working with stack variables (automatic (de)allocation when I walk through blocks), or it’s just a stupid jump?
Question 1:
The code in … can write to
stack_var. However, this variable is uninitialized because the execution flow jumped over the initialization, so the code should not read from it without having written to it first.From the C99 standard, 6.8:3
My compiler compiles the function below to a piece of assembly that sometimes returns the uninitialized contents of
x:Question 2:
Yes, you can expect the memory reserved for
stack_varto be reclaimed as soon as the variable goes out of scope.