How to initialize a struct in accordance with C programming language standards

In (ANSI) C99, you can use a designated initializer to initialize a structure: MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 }; Other members are initialized as zero: “Omitted field members are implicitly initialized the same as objects that have static storage duration.” (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

Difference between ‘struct’ and ‘typedef struct’ in C++?

In C++, there is only a subtle difference. It’s a holdover from C, in which it makes a difference. The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct/union/enum) and ordinary identifiers (for typedef and other identifiers). If you just said: … Read more

What are the differences between struct and class in C++?

You forget the tricky 2nd difference between classes and structs. Quoth the standard (§11.2.2 in C++98 through C++11): In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class. And just for completeness’ sake, the more widely … Read more

Structure padding and packing

Padding aligns structure members to “natural” address boundaries – say, int members would have offsets, which are mod(4) == 0 on 32-bit platform. Padding is on by default. It inserts the following “gaps” into your first structure: struct mystruct_A { char a; char gap_0[3]; /* inserted by compiler: for alignment of b */ int b; … Read more

Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs: Mis-aligned access might be a hard error (often SIGBUS). Mis-aligned access might be a soft error. Either corrected in hardware, for a modest performance-degradation. Or corrected by emulation in software, for a severe performance-degradation. In … Read more