Behavior of uninitialized local char?

2019-07-04 13:47发布

问题:

If you have lets say a local int that is uninitialized, then its gets an undefined value but if you have a local char variable should that not have an undefined value as well? Of course 0 could be that undefined value, but i was wondering if char is any different, since all related info i find is about int and the program below just outputs 0 when the char variable is cast to an int. Im using GCC 4.7 with no flags.

int main()
{
char test1;
int test2;

std::cout<<test2; //garbage
std::cout<<std::endl;
std::cout<<(int)test1; //0
    return 0;
}

回答1:

Uninitialised means really uninitialised. Just because you consistently get a particular value on your machine at a particular time, doesn't mean that will always be the case all the time on all machines.

You can verify that nothing is initialising your variable by dumping the assembly code for your function and inspecting it.



回答2:

Local variables get their initial values from whatever random data is in the stack space they occupy at that moment. There is no guarantee that space contains zeros.



回答3:

If you have lets say a local int that is uninitialized, then its gets an undefined value

No, that isn't the right way to think about it. Your local variable doesn't get an undefined value, it gets no value whatsoever. Subsequently querying such an uninitialized variable invokes undefined behavior.

Your program won't necessarily print "0". It won't necessarily print any number, or even anything at all. Granted, on typical computers, using typical compilers, your program will print some number, but within the scope of the C++ language, we can't make any prediction about what your program will do or not do.