mercredi 24 octobre 2018

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!

Aucun commentaire:

Enregistrer un commentaire