tags:

views:

289

answers:

2

I am curious to know why bit fields with same data type takes less size 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, 64bit x86 machine.

A bit machine/compiler level answer would be great.

+4  A: 

Alignment.

Your compiler is going to align variables in a way that makes sense for your architecture. In your case, char, int, and bool are different sizes, so it will go by that information rather than your bit field hints.

There was some discussion in this question on the matter.

The solution is to give #pragma directives or __attributes__ to your compiler to instruct it to ignore alignment optimizations.

greyfade
Note that bit fields don't really have alignment requirements, though.
Lars Wirzenius
No, but the compiler is under no obligation to pack them.
greyfade
See ISO14882:2003, §9.6, paragraph 1.
greyfade
Another reason why learning about machine architecture and compiler construction is still useful to programmers, in spite of the denials of same by some on SO.
Craig S
+3  A: 

The C standard (1999 version, §6.7.2.1, page 102, point 10) says this:

An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit.

There does not seem to be any wording to allow the packing to be affected by the types of the fields. Thus I would conclude that this is a compiler bug.

gcc makes a 4 byte struct in either case, on both a 32-bit and a 64-bit machine, under Linux. I don't have VS and can't test that.

Lars Wirzenius
C++03, §9.6, paragraph 1 says, "Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit." It seems mahesh is using a C++ compiler.
greyfade
On the other hand, he also tagged this as a C question, not just C++. I guess the answer is different for C and C++.
Lars Wirzenius
I would be wary of claiming this as a "bug" since you were quoting from the ISO C99 standard. MSVC++ makes no claim of adherence to C99. It supports ISO C90/ANSI C89.
Clifford
PS: The use of types other than int or unsigned in bit-fields is an extension with respect to C89/90 so all bets are off with respect to behaviour.
Clifford
If MSVC++ doesn't support a decade old standard... it doesn't sound very impressive, does it?
Lars Wirzenius