4

Possible Duplicate:
What does 'unsigned temp:3' means

I have been trying to learn raw socket programming in C and have come across this:

unsigned char      iph_ihl:5, iph_ver:4;

I am confused about what the ':' does. Does it even do anything? Or is it just part of the variable's name?

Community
  • 1
  • 1
Hudson Worden
  • 2,263
  • 8
  • 30
  • 45

3 Answers3

6

You're looking at bitfields. Those definitions have to be inside a structure, and they mean that iph_ihl is a 5-bit field and iph_ver is a 4-bit field.

Your example is a bit strange, since an unsigned char would be an 8-bit type on most machines, but there are 9 bits worth of fields declared there.

In general bitfields are pretty non-portable, so I would recommend against their use, but you can read more about them here.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Can this only be done with chars? – Hudson Worden Jan 09 '12 at 04:23
  • You can use any integer type. – Carl Norum Jan 09 '12 at 04:24
  • @Hudson: You can use `signed int`, `unsigned int`, `int` (which, depending on the implementation, may be treated as signed or unsigned), or `bool`/`_Bool`. Support for any other types is an implementation-defined extension. – Keith Thompson Jan 09 '12 at 04:53
  • What's odd about using `unsigned char`, as long as each bit field is 8 bits or less? (Apart from the fact that `unsigned char` bit fields are non-standard.) – Keith Thompson Jan 09 '12 at 04:56
  • @Keith, it just seems strange, since normally the goal of bitfields is to pack multiple fields into a single integer type's space. Using them just to create 4- or 5-bit types like in the example is something I haven't seen very often. – Carl Norum Jan 09 '12 at 05:44
  • The type used to declare the field pretty much just determines if it's signed or unsigned. I don't understand your middle paragraph at all, the fields don't have to fit in a single variable of type `unsigned char`. – unwind Jan 09 '12 at 08:25
1

It is bit fields..See this good documentation about C bit fields..It is normally used in memory constrained situations (example embedded programming), to tightly pack our usage..

Important point Bit fields do not have addresses—you can't have pointers to them or arrays of them

Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
0

Apart from the above mentioned answers, you can take a look at this for a good introduction on bit fields. One thing to note: bit fields in c can be used only on integer types. Using bit fields will not only make your program be non-portable, it will also be compiler-dependent.

Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98