Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does member `float x` get initialized with `0.` for the objects `a` and `b` in main()? [duplicate]

Could somebody indicate which clause in the Standard supports the following behavior obtained in Coliru, for the snippet:

#include <iostream>

class A
{
    int i;
    float x;

    public:
    A() : i(10) {}
    A(int i) : i(i) {}
    int GetI() { return i; }
    float GetF() { return x; }
};


int main()
{
    A a;
    A b(1);
    A x{};
    A y{1};
    std::cout << a.GetI() << '\n';
    std::cout << a.GetF() << '\n';
    std::cout << b.GetI() << '\n';
    std::cout << b.GetF() << '\n';
    std::cout << x.GetI() << '\n';
    std::cout << x.GetF() << '\n';
    std::cout << y.GetI() << '\n';
    std::cout << y.GetF() << '\n';
}

The code prints:

10
0 <-- Shouldn't be unknown?
1
0 <-- idem
10
0
1
0

Edit:

This paragraph was obtained from the TCPL 4th edition, page 490:

For this, the rules are not as clean as we might like. For statically allocated objects (§6.4.2), the rules are exactly as if you had used {}, so the value of alpha is {"","",0}. However, for local variables and free-store objects, the default initialization is done only for members of class type, and members of built-in type are left uninitialized, so the value of beta is {"","",unknown}.

Mr. Stroustrup doesn't say anything about undefined behavior.

like image 593
Wake up Brazil Avatar asked Dec 24 '13 22:12

Wake up Brazil


1 Answers

0 is one of the possible arbitrary value an uninitialized variable can acquire: the program has undefined behavior. Given that there is a fair chance that memory starts off zero initialized, 0 is a likely outcome: the IEEE 754 representation for 0 happens to be all zeros. There is, however, no guarantee that the value will be 0.

like image 95
Dietmar Kühl Avatar answered Oct 07 '22 01:10

Dietmar Kühl