3

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

struct sample{
    int x    :2;
    char y   :4;
};

What does the colon operator do in the above code?

Community
  • 1
  • 1
subbu
  • 611
  • 1
  • 8
  • 5
  • Don't forget to accept the most useful answer to each of the other questions you've asked. See the FAQ and the checkmark (tick) by each answer. – Jonathan Leffler Sep 12 '11 at 06:06
  • Keep in mind that (a) the signedness of `int x :2;` is implementation-defined (use `signed int` or `unsigned int`), and (b) bit fields of type `char` are non-standard, and there's no real reason not to declare `y` as `unsigned y :4;`. – Keith Thompson Sep 12 '11 at 07:03

1 Answers1

7

It is used to specify bit fields. The size of the field is given in bits. The layout is compiler-specific.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Damnit, whenever I'm fact-checking my answer someone always ninja's me to it :(, good job. – Avery3R Sep 12 '11 at 06:04
  • @Jonathan Leffler - do you mean that the order of `x` and `y` in the following struct is not guaranteed? - `struct layout {int x:2; int y:2};` – MByD Sep 12 '11 at 06:07
  • 1
    @MByD: I mean that the C standard does not define whether the bits for x are the most significant or least significant bits. It does not define whether those bit fields are stored in 1 byte, or 2 bytes or 4 bytes (or any other number of bytes). It does not define whether the values are signed or unsigned (so you can't tell whether the range of x is -2..+1 or 0..3, or some other range if not using 2's complement arithmetic); likewise for y. All these properties are implementation-defined (so they are known and fixed, but you can't tell what the answer is without looking at the compiler manual). – Jonathan Leffler Sep 12 '11 at 06:18