Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Initialization of local variables

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.

like image 992
m0bi5 Avatar asked Feb 03 '26 00:02

m0bi5


1 Answers

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.

like image 85
Sourav Ghosh Avatar answered Feb 05 '26 14:02

Sourav Ghosh