1

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!

Yi Fan
  • 13
  • 2
  • 2
    I'm afraid I've never seen `nullptr` do that, but you haven't initialized num to anything, so if your system doesn't automatically zero memory mapped for programs as part of its security model, `num` could be literally anything and only happen to be zero since zero is a common value to be in memory. – awiebe Oct 25 '18 at 02:50
  • The initial value of an uninitialized variable is undefined. It might be zero it might not be and it won't depend on the pointer and if it does it is still undefined-behavior, with no guarantees, possibly a compiler quirk, that you should never depend on. Always initialize your variables. – Aluan Haddad Oct 25 '18 at 02:51
  • see [Has C++ standard changed with respect to the use of indeterminate values and undefined behavior in C++14?](https://stackoverflow.com/q/23415661/1708801) – Shafik Yaghmour Oct 25 '18 at 04:30
  • The real question is why are you expecting to find any coherence when reading uninitiated variables. There's nothing strange about it, you are simply invoking undefined behavior. – Havenard Oct 25 '18 at 04:45
  • I see, so it's just a weird undefined behavior. I should avoid it instead of trying to understand it. Thanks! – Yi Fan Oct 26 '18 at 20:16

2 Answers2

3

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • I always thought undefined behavior means random result. But it seems it can give the same result every time but has no reason at all. Since there is no point trying to understand it, I guess I'll just try to always avoid them. Thanks – Yi Fan Oct 26 '18 at 20:24
0

First of all, nullptr is not equal to 0. If you remove the code (ptr == nullptr) from std::cout and just initialize the ptr as nullptr and print ptr then you will see that nothing is printed.

Archit J
  • 152
  • 8