Reputation: 1670
I know that this is all implementation specific, but for the sake of example let's assume that for a certain modern computer:
int
takes up a whole WORD
short
takes up half a WORD
Will the short actually take up less memory, or will it just be stored in the first half of a WORD with unused memory in the second half? Will a C/C++ compiler ever try to pack two or more smaller variables into a single WORD, or will this space always be wasted?
Upvotes: 2
Views: 1143
Reputation: 264631
That depends a lot on usage.
But if you have a structure that is using the same size objects.
struct X
{
short var1;
short var2;
}
Then most likely there will be no padding in the above structure (no guarantee but it's highly likely there is no padding).
Because of point 3 above: If you want to help your compiler optimally pack a structure then it definitely makes it easier for the compiler to order your members from largest to smallest as this makes the packing without needing padding much easier (but the standard does not impose any requirements on padding).
// if we assume sizeof(int) == 8
struct Y
{
char x; // 1 byte;
// Compiler will (prob) insert 7 bytes of padding here.
// to make sure that y is on an 8 byte boundry
// for most effecient reads.
int y;
char z; // 1 byte
// Compiler will (prob) insert 7 bytes of padding here.
// to make sure that the whole structure has a size
// that is a multiple of 8 (the largest object)
// This allows for optimal packing of arrays of type
// Y.
};
The compiler can still achieve optimal packing and fast access if you arrange the object like this:
struct Y
{
int y;
char x;
char z;
// probably add 6 bytes of padding.
// So that we get optimal access to objects in an array.
};
for the sake of example let's assume that for a certain modern computer:
If we assume a modern good compiler like clang or g++ on normal standard architecture machine. Even if we assume not optimizing for speed.
Will the short actually take up less memory
Yes. Modern compiler will pack objects as much as possible and would probably use only the memory required. Note: most compiler be default will optimize for speed so will maintain optimal alignment for speed so will pad if they have to (if objects in a structure that they can not re-order have different sizes).
or will it just be stored in the first half of a WORD with unused memory in the second half?
Unlikely unless there is some requirement that the compiler must maintain. Like order of a structure.
Will a C/C++ compiler ever try to pack two or more smaller variables into a single WORD
Yes. All the time. The default is usually. 1 Optimize for speed. 2 Optimize for size (not always mutually exclusive). You can also force modern compilers to optimize for space and pack structures without padding.
or will this space always be wasted?
Unlikely.
Upvotes: 3