Instead of writing a structure like,
typedef struct {
uint8 len; // Command length (cmd ... crc)
uint8 cmd; // Command code
uint8 data_length; // Data length
uint8 data[12]; // Data: max 12 Byte
uint8 crc_h; // CRC value MSB
uint8 crc_l; // CRC value LSB
}CMD_TYPE;
can I write it like this ?
typedef struct { uint8 len, cmd, data_length, data[12], crc_h, crc_l; }CMD_TYPE;
If it is possible then why aren’t people grouping similar members?!
what would happen to the memory allocation scheme, also is there any hidden side effects to changing the order of members other than memory loss(due to padding if i am right!).
Pardon me if this seems so silly.
You can write both ways, but you’ll notice that the first way is more readable than the second one, and since data structures are very important in C it is in practice preferable to define them in a more verbose way.
The way you write your
structdeclaration (in one line per field, or every fields of the same type on the same line) don’t inpact what happens at runtime.The order of member fields inside
structis very important.Padding, or the
sizeofof yourstruct, or its alignment depend only of fields and their order (and of the target processor and ABI), not of the way you write them.