1

I wonder why do I get zero as an output of this code:

#include <iostream>    

class C
{
public:
    int m;
    C() {}
};

int main ()
{ 
    C c;
    std::cout << c.m << '\n';
    return 0;
}

I've always thought that a member of a built-in type is not initialized when it is not mentioned in a constructor initializer list. Also, when building in debug mode, the result is what I expect — some non-zero value. Why do I get zero in release mode and don't — in debug? Why do I get zero at all?

Oleksa
  • 635
  • 5
  • 15
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/226011/discussion-on-question-by-oleksijp-why-a-zeroed-member-of-a-built-in-type-on-def). – Machavity Dec 15 '20 at 22:54

1 Answers1

2

An int can only contain integer values. So what should a hypothetical "unitialized value" be?

So what unintialized means for integers in C++ is that the value isn't guaranteed in any way. It might be 0 sometimes. It's might be some other integer value other times. The uninitialized value might be different after you make some code changes. It might be different from one run on the program to the next. Or it might appear to stay the same, by chance. No guarantee of anything.

In debug mode the compiler might try to help by setting it to an unusual value to help you recognize the fact that's it's uninitialized.

TheUndeadFish
  • 8,058
  • 1
  • 23
  • 17
  • It's not necessarily true that an `int` can only contain integer values. An `int` type can (before C++20) contain unused bits at the end. It's plausible that such bits could be used to denote an uninitialised `int`. – Bathsheba Dec 15 '20 at 21:27
  • Interesting. I hadn't considered whether the C++ standard could allow such a thing in theory. Though in practice I expect that isn't a likely choice for an implementation to go with. – TheUndeadFish Dec 15 '20 at 21:41