The values of uninitialized members of a C struct are not guaranteed to be 0. To explicitly initialize these members, use an initialization list:
struct Snapshot { double x; int y; }; Snapshot s = {0, 0}; // Explicitly initialize members to 0
Alternatively, you can initialize the struct using the {} syntax:
Snapshot s = {}; // Value initializes all members to 0
Note that using {} for value initialization works recursively, even for nested structs:
struct Parent { Snapshot s; }; Parent p = {}; // Value initializes both p and p.s to 0
If the struct has constructors, you must explicitly initialize the members in those constructors:
struct Snapshot { int x; double y; Snapshot(): x(0), y(0) { } // Initialize members in the constructor };
Alternatively, you can use the default value initialization syntax x(), y() to disregard the type and assign an appropriate initial value (0 for int, 0.0 for double, etc.):
Snapshot(): x(), y() { } // Value initializes both x and y to 0
This can be especially useful for templates.
The above is the detailed content of Are C Struct Members Initialized to Zero by Default?. For more information, please follow other related articles on the PHP Chinese website!