csocketssyntax

In C what does ':' do?


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?


Solution

  • 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.