Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this program produce odd output when the variable is uninitialized?

Tags:

int main() {     int j = 0;     int i = 0;     for (j = 0; j < 5; j++) {         printf("Iteration %d :  %d ", j + 1, i);         int i;         printf("%d", i);         i = 5;         printf("\n");     } } 

The above code generates the following output:

Iteration 1 :  0 0 Iteration 2 :  0 5 Iteration 3 :  0 5 Iteration 4 :  0 5 Iteration 5 :  0 5 

I'm not able to understand why the second printf value in iterations 2,3,4,5 is 5.

My understanding of why the first value is 0 in each iteration is that the scope of i in the for loop is local and it is destroyed as soon as we go into a new iteration as i was declared in the for loop.

But I'm not able to figure out why this value becomes 5 at the second printf.

like image 228
Milan Avatar asked Feb 23 '17 15:02

Milan


People also ask

What happens if a variable is not initialized in C?

If a variable is declared but not initialized or uninitialized and if those variables are trying to print, then, it will return 0 or some garbage value. Whenever we declare a variable, a location is allocated to that variable.

What does it mean when a variable is uninitialized in c++?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.


2 Answers

The behaviour of your program is undefined.

The inner scope i is not initialised at the point it's read.

(What might be happening is that the reintroduced i on subsequent iterations occupies the same memory as the previous incarnation of the inner i, and the uninitialised memory on the first iteration corresponds to 0. But don't rely on that. On other occasions, the compiler might eat your cat.)

like image 157
Bathsheba Avatar answered Sep 16 '22 17:09

Bathsheba


The second printf in your program is printing garbage value from uninitialized local variable i. In general case the behavior is undefined.

By accident, storage location that represents your i (memory cell or CPU register) is the same on each iteration of the cycle. By another accident, the body of your cycle is executed as a single compound statement for each iteration (as opposed to unrolling the cycle and executing all iterations at the same time in interleaved fashion). By yet another accident, the storage location of i keeps its old value from the previous iteration. So, the garbage that you are printing matches the last stored value from that location on the previous iteration of the cycle.

That's why you see 5 in local i on each iteration besides the first. On the first iteration that garbage value happened to be 0.

like image 29
AnT Avatar answered Sep 18 '22 17:09

AnT