Home > Article > Backend Development > Why is dot-notation initialization not supported for structs in C ?
C Structure Initialization: An Alternative Approach
In C , unlike C, it's not possible to initialize structures using the dot notation shown below:
<code class="c++">struct address { int street_no; char *street_name; char *city; char *prov; char *postal_code; }; // Invalid C++ syntax address temp_address = { .city = "Hamilton", .prov = "Ontario" };</code>
This query raises several questions:
Technical and Practical Reasons
Technically, there is no underlying limitation preventing the implementation of dot-notation initialization for structs in C . However, the C Standards Committee has chosen not to include this feature for several practical reasons:
Alternative Approaches for Readability
To enhance readability, consider the following alternatives:
<code class="c++">address temp_address = { 0, // street_no nullptr, // street_name "Hamilton", // city "Ontario", // prov nullptr, // postal_code };</code>
<code class="c++">struct address { address(int sn, char* stn, char* c, char* p, char* pc): street_no(sn), street_name(stn), city(c), prov(p), postal_code(pc) {} int street_no; char *street_name; char *city; char *prov; char *postal_code; }; address temp_address(0, nullptr, "Hamilton", "Ontario", nullptr);</code>
These alternatives provide explicit and readable initialization while adhering to C 's type safety and consistency principles.
The above is the detailed content of Why is dot-notation initialization not supported for structs in C ?. For more information, please follow other related articles on the PHP Chinese website!