Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C++ syntax question about colon

Tags:

I just saw a code snippet with a piece of syntax that I have never seen before. What does bool start : 1; mean? I found it inside a class definition in a header file.

like image 351
swegi Avatar asked Feb 10 '10 08:02

swegi


People also ask

What is colon and question mark in C?

Unlike all other operators in Objective-C—which are either unary or binary operators—the conditional operator is a ternary operator; that is, it takes three operands. The two symbols used to denote this operator are the question mark ( ? ) and the colon ( : ).

When colon is used in C programming?

It's commonly used to pack lots of values into an integral type. In your particular case, it defining the structure of a 32-bit microcode instruction for a (possibly) hypothetical CPU (if you add up all the bit-field lengths, they sum to 32). This prints out 7, which is the three bits making up the alu bit-field.

What does question mark colon mean?

As everyone referred that, It is a way of representing conditional operator if (condition){ true } else { false }

What is colon in struct in C?

They can be used as "dummy" fields, for alignment purposes. An unnamed bit field whose width is specified as 0 guarantees that storage for the member following it in the struct-declaration-list begins on an int boundary.


1 Answers

struct record {     char *name;     int refcount : 4;     unsigned dirty : 1; }; 

Those are bit-fields; the number gives the exact size of the field, in bits. (See any complete book on C for the details.) Bit-fields can be used to save space in structures having several binary flags or other small fields, and they can also be used in an attempt to conform to externally-imposed storage layouts. (Their success at the latter task is mitigated by the fact that bit-fields are assigned left-to-right on some machines and right-to-left on others).

Note that the colon notation for specifying the size of a field in bits is only valid in structures (and in unions); you cannot use this mechanism to specify the size of arbitrary variables.

  • References: K&R1 Sec. 6.7 pp. 136-8
  • K&R2 Sec. 6.9 pp. 149-50
  • ISO Sec. 6.5.2.1
  • H&S Sec. 5.6.5 pp. 136-8
like image 162
serialx Avatar answered Sep 24 '22 07:09

serialx