It is impossible to do it with standard C++, but it is possible to use a compiler specific pragma or attribute for your structure.
in VC++, it is #pragma pack
Also to get size of 2 only, you have to do this:
#pragma pack(1)
struct s{
unsigned short s1: 15;
unsigned short b1: 1;
};
With #pragma pack
on your code as follows:
struct S
{
unsigned short x : 15;
bool a : 1;
};
A hypothetical memory layout would be:
----------------------
+ 1 | 2 | 3 | 4 | 5 | ..
+ x | a |
+---------------------
Hence it occupies 3 bytes
changing bool a
to unsigned short a
you get this:
-------------------------
+ 1 | 2 | 3 | 4 | 5| ..
+ x |a|
-------------------------
Which occupies only 2 bytes.
The compiler decides that, since the second short is only taking 1 bit, it is possible to just squeeze the structure into 2 bytes. But if a structure member of another type is used (such as bool
in your implementation of S
) the compiler thinks, since the types are different, it cannot actually squeeze the 1 bit into unsigned short
(because it is crossing the type boundary - unfortunately implementation defined). Hence you get 3
bytes for sizeof()
instead of 2.