C 構造体の「:」(コロン) はどういう意味ですか? [重複] 質問する

C 構造体の「:」(コロン) はどういう意味ですか? [重複] 質問する
struct _USBCHECK_FLAGS
    {
        unsigned char   DEVICE_DEFAULT_STATE       : 1;
        unsigned char   DEVICE_ADDRESS_STATE       : 1;
        unsigned char   DEVICE_CONFIGURATION_STATE : 1;
        unsigned char   DEVICE_INTERFACE_STATE     : 1;
        unsigned char   FOUR_RESERVED_BITS         : 8;
        unsigned char   RESET_BITS                 : 8;
    } State_bits;

:1と はどういう:8意味ですか?

ベストアンサー1

これらはビットフィールドです。基本的に、コロンの後の数字は、そのフィールドが使用するビット数を表します。MSDNからの引用ビットフィールドの記述:

定数式は、フィールドの幅をビット単位で指定します。宣言子の型指定子は unsigned int、signed int、または int でなければならず、定数式は負でない整数値でなければなりません。値が 0 の場合、宣言には宣言子がありません。ビット フィールドの配列、ビット フィールドへのポインター、およびビット フィールドを返す関数は使用できません。オプションの宣言子は、ビット フィールドの名前を指定します。ビット フィールドは、構造体の一部としてのみ宣言できます。アドレス演算子 (&) は、ビット フィールド コンポーネントには適用できません。

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\ntest2: %d\ntest3: %d\ntest4: %d\n", sizeof(test1), sizeof(test2), sizeof(test3), sizeof(test4));

test1: 4

test2: 2

test3: 1

test4: 4

おすすめ記事