I am using cpp.sh to compile and run this code. I am expecting the value of number
to be either default initialized to 0
or some garbage value. However, in the constructor, even though the if
condition is false, the value of number
is still initialized to 10
. Can someone explain to me what's happening?
#include <iostream>
class Number
{
int number;
public:
Number(std::string s)
{
if (s == "foo")
{
number = 10;
}
}
int getNumber()
{
return number;
}
};
int main()
{
Number n("bar");
std::cout << n.getNumber() << std::endl;
}
From clause 9 in [dcl.decl]
If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced
Value 10 is placed just as optimization done by compiler to eliminate conditional statement.
It's a compiler optimization on the constructor. You can check it changing the optimization level.
As the data member number
is not initialized, the value of the variable is following the UB rule. That said the compiler (cpp.sh cited above) optimize the constructor at Full (-O2) assigning always 10, as it's times cheaper than trying to do the string comparison and make a jump or an assignment.
Tried to change the optimization level to normal
and it didn't happen.
Tried with VS 2017, debug & release and it doesn't happen.
It's an optimization done by the compiler. Specifically by the compiler used by cpp.sh at Full (-o2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With