Value Initialization of Struct Members in C
Consider the following struct:
struct Snapshot { double x; int y; };
If the struct is declared without initialization, are its members automatically set to 0?
Answer:
No, members are not automatically initialized to 0. To set them to 0, explicit initialization is required:
Snapshot s = {0,0};
Other Initialization Options:
Snapshot s = {}; // All members set to 0
struct Snapshot { int x = 0; double y = 0.0; }; Snapshot s; // x = 0, y = 0.0
struct Snapshot { Snapshot(int x, double y) : x(x), y(y) { } }; Snapshot s(0, 0.0); // x = 0, y = 0.0
Note: Constructor initialization is not possible if there are aggregate initializer lists present in the struct declaration.
The above is the detailed content of Are C Struct Members Automatically Zero-Initialized?. For more information, please follow other related articles on the PHP Chinese website!