Why are bit fields for the same data types smaller than bit fields for mixed data types

I am curious to know why bit fields with the same data type are smaller than with mixed data types.

struct xyz 
{ 
  int x : 1; 
  int y : 1; 
  int z : 1; 
}; 


struct abc 
{ 
  char x : 1; 
  int y : 1; 
  bool z : 1; 
}; 

sizeof (xyz) = 4 sizeof (abc) = 12.

I am using VS 2005, a 64bit x86 machine.

The answer to the bit / compiler will be great.

+5
source share
3 answers

Alignment.

Your compiler will align the variables in a way that makes sense for your architecture. In your case char, intthey boolhave different sizes, so they will be processed with this information, and not with hints in the bit field.

.

, #pragma __attributes__ , .

+4

C ( 1999 , §6.7.2.1, . 102, 10) :

, . , -, - .

, - , . , , .

gcc 4- , 32-, 64- , Linux. VS .

+3

. , , sizeof . xyz sizeof 4, .. Int. abc 4 int.

, :   struct abc   {     char a: 1;    char b: 1;    bool c: 1;   };

sizeof (abc) 1 4. 1, 1 char.

.

Link for output based on old structure: Visit http://codepad.org/6j5z2CEX

Link for output based on the above structure: Visit http://codepad.org/fqF9Ob8W

To avoid such problems for sizeof structures, we must properly package structures using the #pragma pack macro.

0
source

All Articles