#include <iostream> class MyClass { public: MyClass() : mFirst() { } int mFirst; int mSecond; }; int main() { MyClass mc; std::cout << "mc.mFirst: " << mc.mFirst << std::endl; std::cout << "mc.mSecond: " << mc.mSecond << std::endl; int a; std::cout << "a: " << a << std::endl; return 0; }
What is the expected result of this program?
I would think that only MyClass.mFirst would be initialized to zero. However, GCC initializes them all to zero, even when optimization is turned on:
$ g++ -o test -O3 main.cpp $ ./test mc.mFirst: 0 mc.mSecond: 0 a: 0
I'd like to know:
- How is each value initialized according to the C ++ standard?
- Why does the GCC initialize them all to zero?
Update
According to Erik, the values ββare zero because my stack contains zeros. I tried to make the stack non-zero using this construct:
int main() { // Fill the stack with non-zeroes { int a[100]; memset(a, !0, sizeof(a)); } MyClass mc; std::cout << "mc.mFirst: " << mc.mFirst << std::endl; std::cout << "mc.mSecond: " << mc.mSecond << std::endl; int a; std::cout << "a: " << a << std::endl; return 0; }
However, the output remains unchanged:
mc.mFirst: 0 mc.mSecond: 0 a: 0
Can someone explain why?
Update 2
Ok, I figured it out. GCC probably optimized unused variables.
This app shows expected behavior:
Output:
$ g++ -o test main.cpp $ ./test mc.mFirst: 0 mc.mSecond: 2 a: 3
source share