These indicate bit-fields with the length being denoted after the colon
struct clap
{
int i:2; // length 2
int j:2; // length 2
int k:3; // length 3
};
Bitfields save on space. Try computing sizeof(clap)
and you'll find it is 4 bytes on gcc 4.7. The reason it is not 1 byte (2 + 2 + 3 = 7 bits < 1 byte), is that compilers also align structs on certain boundaries depending on the underyling type of the bitfields. E.g. changing int
to short
or char
as the underlying type of the bitfields will reduce the total size of clap
to respectively 2 and 1 byte(s) (on gcc 4.7 again).
This should be compared to storing 3 full integers typically takes 12 bytes (if an int is 4 bytes). OTOH, bit-fields can make your code slower because addressing the members entails shifting and unpacking the bitfields.
The sign problem arises because the 2-bits two's complement of 2 is equal to -2. Extending the code to int j:3
will output 2
.