Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

c++ - ":" (colon) in C struct - what does it mean?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Those are bit fields. Basically, the number after the colon describes how many bits that field uses. Here is a quote from MSDN describing bit fields:

The constant-expression specifies the width of the field in bits. The type-specifier for the declarator must be unsigned int, signed int, or int, and the constant-expression must be a nonnegative integer value. If the value is zero, the declaration has no declarator. Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure. The address-of operator (&) cannot be applied to bit-field components.

Unnamed bit fields cannot be referenced, and their contents at run time are unpredictable. 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.

This example defines a two-dimensional array of structures named screen.

struct 
{
    unsigned short icon : 8;
    unsigned short color : 4;
    unsigned short underline : 1;
    unsigned short blink : 1;
} screen[25][80];

Edit: another important bit from the MSDN link:

Bit fields have the same semantics as the integer type. This means a bit field is used in expressions in exactly the same way as a variable of the same base type would be used, regardless of how many bits are in the bit field.

A quick sample illustrates this nicely. Interestingly, with mixed types the compiler seems to default to sizeof (int).

  struct
  {
    int a : 4;
    int b : 13;
    int c : 1;
  } test1;

  struct
  {
    short a : 4;
    short b : 3;
  } test2;

  struct
  {
    char a : 4;
    char b : 3;
  } test3;

  struct
  {
    char a : 4;
    short b : 3;
  } test4;

  printf("test1: %d
test2: %d
test3: %d
test4: %d
", sizeof(test1), sizeof(test2), sizeof(test3), sizeof(test4));

test1: 4

test2: 2

test3: 1

test4: 4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...