Search code examples
carraysloopswhile-loopgarbage

Why the following code printing garbage value?


I am not able to understand why the following code printing garbage value

#include <stdio.h> 

void main(){
 int arr[5],i=0;
 while(i<5)
    arr[i]=++i;
for(i=0;i<5;i++)
    printf("%d",arr[i]);
 }

Solution

  • The statement

    arr[i]=++i;
    

    is effectively equivalent to

    i = i + 1;
    arr[i] = i;
    

    Which means you will not initialize the first element (at index 0) in the array. What's worse is that you will write at index 5 as well, and that's out of bounds and will lead to undefined behavior.

    Uninitialized local variables will have an indeterminate value, which could be seen as random or garbage.

    I recommend that you have a for loop like the one used for printing the values for your initialization as well:

    for (i = 0; i < 5; ++i)
        arr[i] = i + 1;