2

I have the following code snippet.

int j;
printf("%d",j);

As expected, I get a garbage value.

32039491

But when I include a loop in the above snippet, like

int j;
print("%d",j);
while(j);

I get the following output on multiple trials of the program.

0

I always thought local variables are initialized to a garbage value by default, but it looks like variables get auto initialized when a loop is used.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
m0bi5
  • 8,900
  • 7
  • 33
  • 44

2 Answers2

8

It is having indeterminate value. It can be anything.

Quoting C11 §6.7.9

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]

Automatic local variables, unless initialized explicitly, will contain indeterminate value. In case you try to use a variable while it holds indeterminate value and either

  • does not have the address taken
  • can have trap representation

the usage will lead to undefined behavior.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • If the variables in the OPs code have automatic storage duration (which we can't tell), accessing them is undefined behavior, but not because of trap representations. [See this](http://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior-in-c/40674888#40674888). – Lundin Jan 19 '17 at 07:17
  • @Lundin Thanks for the pointer sir, updated my answer, is it better now? – Sourav Ghosh Jan 19 '17 at 07:24
4

As expected, I get a garbage value.

Then your expectation is unjustifiably hopeful. When you use the indeterminate value of an uninitialized object, you generally get (and for your code snippets alone you do get) undefined behavior. Printing a garbage value is but one of infinitely many possible manifestations.

I always thought local variables are initialized to a garbage value by default, but it looks like variables get auto initialized when a loop is used.

You thought wrong, and you're also drawing the wrong conclusion. Both of your code snippets, when standing alone, exhibit undefined behavior. You cannot safely rely on any particular result.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • You can't know that it is undefined behavior because we can't tell the scope based on the OPs code. Similarly, you can't assume that the OP is using a system with trap representations. Therefore this is possibly incorrect: "When you use the indeterminate value of an uninitialized object, you get undefined behavior". [See this](http://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior-in-c/40674888#40674888). – Lundin Jan 19 '17 at 07:14
  • @Lundin, thanks for pointing that out. I have qualified the answer a bit to allow myself what I think is sufficient weasel room. Anyone interested in why I do so (i.e. the details of when the behavior is not undefined) can follow the link you kindly provided. – John Bollinger Jan 19 '17 at 16:51