Search code examples
cvariable-declarationgarbage

why garbage value is stored during declaration?


I heard several times that if you do not initialise a variable then garbage value is stored in it.
Say

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

The above code prints any garbage value, but I want to know that what is the need for storing garbage value if uninitialized?


Solution

  • The value of an uninitialized value is not simply unknown or garbage, but indeterminate and evaluating that variable may invoke undefined behavior or implementation-defined behavior.

    One possible scenario (which is probably the scenario you are seeing) is that the variable, when evaluated, will return the value that was previously present in that memory address. Therefore, it's not like garbage is explicitly written to that variable.

    It's worth noting that languages (or even C implementations) that do not exhibit the behavior you're seeing, do so by explicitly writing zeroes (or other initial values) to that area, before allowing you to use it.