Implementations might differ between the actual sizes of types, but on most, types like unsigned int and float are always 4 bytes. But why does a type always occupy a certai
The compiler is allowed to make a lot of changes to your code, as long as things still work (the "as-is" rule).
It would be possible to use a 8-bit literal move instruction instead of the longer (32/64 bit) required to move a full int
. However, you would need two instructions to complete the load, since you would have to set the register to zero first before doing the load.
It is simply more efficient (at least according to the main compilers) to handle the value as 32 bit. Actually, I've yet to see a x86/x86_64 compiler that would do 8-bit load without inline assembly.
However, things are different when it comes to 64 bit. When designing the previous extensions (from 16 to 32 bit) of their processors, Intel made a mistake. Here is a good representation of what they look like. The main takeaway here is that when you write to AL or AH, the other is not affected (fair enough, that was the point and it made sense back then). But it gets interesting when they expanded it to 32 bits. If you write the bottom bits (AL, AH or AX), nothing happens to the upper 16 bits of EAX, which means that if you want to promote a char
into a int
, you need to clear that memory first, but you have no way of actually using only these top 16 bits, making this "feature" more a pain than anything.
Now with 64 bits, AMD did a much better job. If you touch anything in the lower 32 bits, the upper 32 bits are simply set to 0. This leads to some actual optimizations that you can see in this godbolt. You can see that loading something of 8 bits or 32 bits is done the same way, but when you use 64 bits variables, the compiler uses a different instruction depending on the actual size of your literal.
So you can see here, compilers can totally change the actual size of your variable inside the CPU if it would produce the same result, but it makes no sense to do so for smaller types.