In a tutorial it said
If you use the goto statement to jump into the middle of a block, automatic variables within that block are not initialized.
Then in the below code if i can be accessed/declared then why it is not initialised?
int main()
{
goto here;
{
int i=10;
here:
printf("%d\n",i);
}
return 0;
}
ps:output is some garbage value.
There’s no logic behind your question “if
ican be accessed, why…”. Being able to “accessi” isn’t an argument for or against anything. It just means that theprintfstatement is in the same scope asi. However, since you jumped over the initializer, the variable is uninitialized (just as your tutorial says).Reading an uninitialized variable is undefined behaviour, so your program is ill-formed.
The memory for the variable
ihas already been set aside at compile time, since the variable is known to exist inside the inner block. The memory doesn’t get allocated dynamically, as you may be imagining. It’s already there, but it never got set to anything determinate because of thegoto.Rule of thumb: Don’t jump across initializers.