Do different data types in C such as char, short, int, long, float, double have different memory alignment boundaries? In a 32 bit word aligned byte addressable operating system, how is accessing a char or short different from accessing an int or float? In both cases, does the CPU read a full 32-bit word? What happens when an int is not at the boundary? How is it able to read a char at any memory address?
Do different data types in C such as char , short , int ,
Share
The short answer, as others have pointed out, is the compiler will do what’s best for the architecture it’s compiling to. It may align them to the native word size. It may not. Here is a sample program demonstrating this point:
The output:
As you can see, it added some padding between the int and the short. It didn’t bother with the short. In other cases, the reverse may be true. Optimization rules are complex.
And, a warning: The compiler is smarter than you. Don’t play with padding and alignment unless you have a really, really good reason. Just trust that what the compiler is doing is the right thing.