Reputation: 2957
When code is written like that:
#include <iostream>
using namespace std;
struct ID {
char *name;
int age;
};
int main() {
ID a;
cout << (long)(a.name) << endl;
cout << a.age << endl;
// cout << (a.name == nullptr) << endl;
return 0;
}
The result is:
0
0
However, when it's written like that:
#include <iostream>
using namespace std;
struct ID {
char *name;
int age;
};
int main() {
ID a;
cout << (long)(a.name) << endl;
cout << a.age << endl;
cout << (a.name == nullptr) << endl;
return 0;
}
The result seem strange:
140735032148552
1545300144
0
How could these 2 versions vary greatly?
Upvotes: 1
Views: 96
Reputation: 2957
I found the answer myself. Thank you! Pileborg, Daniel and pstanisz. Your answer and comments are of great help to me.
My confusion came from a paragraph in "C++ Primer". In case anybody else has the same confusion, I write my understanding here.
Original word:
Under the new standard, we can supply an in-class initializer for a data member. When we create objects, the in-class initializers will be used to initialize the data members. Members without an initializer are default initialized (§ 2.2.1, p. 43). Thus, when we define Sales_data objects, units_sold and revenue will be initialized to 0, and bookNo will be initialized to the empty string.
-- "C++ Primer 5th edition"
I had thought that fields in a struct follow the same default initialization rule as global variable (i.e. initialized to their zero values). But it actually follows the same rule as local variables in a funtion, which is:
Upvotes: 1
Reputation: 409166
Because of undefined behavior. Defining a local variable will not initialize it, the contents of the structure will be indeterminate, and using it will lead to said UB.
Upvotes: 8