Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goto and automatic variables initializer in c

Tags:

c

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.

like image 618
Vindhya G Avatar asked Jul 12 '12 08:07

Vindhya G


People also ask

What is automatic variable initialization C?

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.

What do you mean by auto initialization?

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.

Which of the following variable needs to be initialized before using it?

Local variables and primitives should be initialized before use because you would know what to expect from the values.

What is the stored in the object if it is not initialized and just declared?

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.


1 Answers

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.

like image 185
Kerrek SB Avatar answered Oct 02 '22 16:10

Kerrek SB