Initialization of C Struct Members
In C , members of a struct are not automatically initialized to 0 or any specific value when declared without an initializer list. This means that the values of uninitialized struct members are indeterminate. To ensure that members are initialized to the desired values, you must explicitly initialize them.
Initialization Methods
There are several ways to initialize members of a struct:
struct Snapshot { double x = 0; int y = 0; };
Snapshot s = {};
struct Snapshot { int x; double y; Snapshot(): x(0), y(0) { } };
Snapshot s; s.x = 0; s.y = 0;
It is important to note that if your struct has user-declared constructors, you cannot use aggregate initialization lists (e.g., {}). In such cases, explicit initialization must be done in the constructors.
The above is the detailed content of How Do I Properly Initialize C Struct Members?. For more information, please follow other related articles on the PHP Chinese website!