Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Weird behavior with String comparison

Tags:

c++

string

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;
}
like image 234
Abdulrahman Alhadhrami Avatar asked Feb 14 '18 08:02

Abdulrahman Alhadhrami


2 Answers

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.

like image 106
Yola Avatar answered Sep 23 '22 14:09

Yola


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)

like image 36
Stefano Buora Avatar answered Sep 24 '22 14:09

Stefano Buora