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.
Automatic variables are variables defined inside a function or block of code without the static keyword. These variables have undefined values if you don't explicitly initialize them. If you don't initialize an automatic variable, you must make sure you assign to it before using the value.
Automatic initialization in Java Java does not initialize non-array local variables (also referred to as automatic variables) . The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.
Local variables and primitives should be initialized before use because you would know what to expect from the values.
Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.
There's no logic behind your question "if i
can be accessed, why...". Being able to "access i
" isn't an argument for or against anything. It just means that the printf
statement is in the same scope as i
. 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 i
has 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 the goto
.
Rule of thumb: Don't jump across initializers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With