Vishnu
Vishnu

Reputation: 33

C Structure: member order and memory allocation

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.

Upvotes: 2

Views: 462

Answers (4)

Vishnu
Vishnu

Reputation: 33

Here you would get to see what the standard says about padding and memory allocation. ![This is directly from ISO C Standard DOC][1][1]: https://i.sstatic.net/UzgDY.png

Upvotes: 0

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 struct declaration (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 struct is very important.

Padding, or the sizeof of your struct, or its alignment depend only of fields and their order (and of the target processor and ABI), not of the way you write them.

Upvotes: 3

Pubby
Pubby

Reputation: 53027

why aren't people grouping similar members?!

Structs are what group similar members. Declaring multiple variables per line is only good when they are strongly related, such as:

int width, height;
char *begin, *end;

Or when you need multiple variables declared in a for loop.

Note that separate lines is much easier to read. Humans read well in short, aligned columns (2-dimensional) rather than long lines (1-dimensional).

what would happen to the memory allocation scheme, also is there any hidden side effects to changing the order of members otherthan memory loss(due to padding if i am right!).

Nothing that I know of.

Upvotes: 1

Stígandr
Stígandr

Reputation: 2902

The only thing your code works is that you have the same type (unsigned byte).

This is not the case most often + it's always nice to have comments above or at the right of each member.

Upvotes: 0

Related Questions