Search code examples
c++11initialization

strange C++ variable initialization


I know this is a basic topic. But I run into a very strange case. Here are two versions of my code: Version 1:

int num;
char *ptr;
std::cout << (num == 0) << std::endl;
std::cout << (ptr == nullptr) << std::endl;

Output:
1
0
Version 2:

int num;
char *ptr = nullptr;
std::cout << (num == 0) << std::endl;
std::cout << (ptr == nullptr) << std::endl;

Output:
0
1
It seems the initial value of the integer num depends on the initialization of the pointer ptr.

Could anyone please explain this? I read some other post but still don't understand. I tried to compile and run many times. The value doesn't seem to be random. It's always this result.

I'm using g++ init.cc -o out -std=c++11

Thanks in advance!


Solution

  • Your program causes undefined behaviour by using the value of an uninitialized variable. As explained by the link, that means anything at all can happen and the output is meaningless. You should not waste time trying to understand the output; instead, fix the program.