We know that there is padding in some structures in C. Please consider the following 2:
struct node1 {
int a;
int b;
char c;
};
struct node2 {
int a;
char c;
int b;
};
Assuming sizeof(int) = alignof(int)
= 4 bytes:
sizeof(node1) = sizeof(node2) = 12
, due to padding.
What is the performance difference between the two? (if any, w.r.t. the compiler or the architecture of the system, especially with GCC)
I would not be surprised if the interviewer's opinion was based on the old argument of backward compatibility when extending the struct in the future. Additional fields (
char
,smallint
) may benefit from the space occupied by the trailing padding, without the risk of affecting the memory offset of the existing fields.In most cases, it's a moot point. The approach itself is likely to break compatibility, for two reasons:
node2
) may not be memory-optimal, but it might well prevent the new fields from accidentally being overwritten by the padding of a 'legacy' struct.