c++cgcc

How does C compilers handle using an uninitialized variable?


As is known to us, using an uninitialized variable is an undefined behavior in C or C++. For example, if we have:

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

It will produce a number that we can't predict.

My question is that how C compilers handle using an uninitialized variable.


Solution

  • This is nothing to do with your compiler, although different compilers may have side-effects that affect the value in a way that appears to be consistent. But regardless, your program has undefined behavior. You did not initialize the value, and so your program's behavior cannot be predicted.

    When you declare the variable x, the compiler only records your intent to store a value large enough to hold int. Now, it doesn't matter where it decides to put this. It might push it onto your stack in memory, or it might choose to keep a CPU register available without using memory at all.

    So, when you ask for the value of x, there is absolutely no way to know what you will get. Most likely you will get whatever dirty value existed previously at whatever location the compiler determined it would set aside. But equally, the compiler could have utterly failed to even decide where x lives, since it was never used, and then do something awful that leads to a program crash, or just about anything else.

    The good news is that you don't have to care about what could happen or why or under what conditions. As a programmer, all you need to care about is that the behavior is undefined. End of story.

    And how to fix this? Easy. Give x a value before you ever try to read its value.