Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable initailization after being called is reflected beforehand

I am learning about scoping of variable in C. Can anyone please explain what is going on below?

  int w;
  printf("\nw=%d\n", w);     
  w =-1;

Despite the fact that I initialized variable 'w' after 'printf', it always gets the value of "-1". This confused me, as I expect it to run sequentially. Hence, it should have printed some random value. *** I also tried changing the value there, and it always read the written value. Hence, it did not randomly show "-1"

For experiment, I again tried the code below.

  int w;
  printf("\nw=%d\n", w);     
  w =-9;
  w =-1;

Now, it reads a value of "2560". As I expect since it was not properly initialized before.

like image 459
Wasu M. Avatar asked Feb 05 '26 12:02

Wasu M.


2 Answers

In your code

int w;
printf("\nw=%d\n", w); 

invokes undefined behavior as you're trying to read the value of an uninitialized (automatic local) variable. The content of w is indeterminate at this point, and the output result is, well, undefined.

Always initialize your local variable before reading (using) the value.


Related: Quoting C11, chapter §6.7.9, Initialization

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

and, related to Undefined behavior, annex §J.2

The value of an object with automatic storage duration is used while it is indeterminate

like image 175
Sourav Ghosh Avatar answered Feb 07 '26 00:02

Sourav Ghosh


The variable in uninitialized. In "C", this means its value is "nondeterministic". In reality, the variable generally gets a value based on what's "laying around" at the memory address to which it gets assigned. In this case, its some value left on the stack.

It just so happens that often you will get consistent results across multiple runs simply due to external factors on which a program should not rely.

like image 34
ash Avatar answered Feb 07 '26 00:02

ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!