8

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

I encountered a problem when I'm reading the code of Clang.

class LangOptions {
public:
    unsigned Trigraphs         : 1;  // Trigraphs in source files.
    unsigned BCPLComment       : 1;  // BCPL-style '//' comments.
    ...
};

This is the first time I saw the syntax " : 1", what's the " : 1" stands for? Thanks!

Community
  • 1
  • 1
Lei Mou
  • 2,562
  • 1
  • 21
  • 29

3 Answers3

7

It's a bitfield, which means that the value will only use one bit, instead of 32 (or whatever sizeof(unsigned) * <bits-per-byte> is on your platform).

Bitfields are useful for writing compact binary data structures, although they come with some performance cost as the compiler/CPU cannot update a single bit, but needs to perform AND/OR operations when reading/writing a full byte.

Macke
  • 24,812
  • 7
  • 82
  • 118
  • 1
    beware with the `*8`, a byte may be more than 8 bits! Thanks for precising the runtime cost :) If I remember correctly there is also a guarantee that arithmetic is performed modulo (2 ^ nb bits) on those fields... but I may be mistaken. – Matthieu M. Jun 10 '11 at 13:46
  • @Matthieu: Thanks. I've edited to match. Also, won't arithmetic be modulo-2 automatically if you store the result in the requried amount of bits? (or maybe that differs slightly on signed vs. unsigned) – Macke Jun 10 '11 at 13:52
2

Trigraphs and BCPLComment use 1 bit only for saving values.

For example,

struct S
{
   signed char type : 2;
   signed char num  : 4;
   signed char temp : 2;
};

uses only 8 bit of memory. struct S may use a single byte or memory. sizeof(S) is 1 for the case of some implementations. But type and temp is equal to 0,1,2 or 3. And num is equal 0,1,2,..., 15 only.

Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88
2

These are bit fields. The "1" is the width in bits.

See the C FAQ for an explanation.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I was going to harp on at you for not linking to the C++ FAQ- but it *doesn't have* an entry for bitfields. – Puppy Jun 10 '11 at 13:44