C++ anonymous structs

巧了我就是萌 提交于 2019-12-22 04:03:06

问题


I use the following union to simplify byte, nibble and bit operations:

union Byte
{
  struct {
    unsigned int bit_0: 1;
    unsigned int bit_1: 1;
    unsigned int bit_2: 1;
    unsigned int bit_3: 1;
    unsigned int bit_4: 1;
    unsigned int bit_5: 1;
    unsigned int bit_6: 1;
    unsigned int bit_7: 1;
  };

  struct {
    unsigned int nibble_0: 4;
    unsigned int nibble_1: 4;
  };

  unsigned char byte;
};

It works nice, but it also generates this warning:

warning: ISO C++ prohibits anonymous structs [-pedantic]

Ok, nice to know. But... how to get this warning out of my g++ output? Is there a possibility to write something like this union without this issue?


回答1:


The gcc compiler option -fms-extensions will allow non-standard anonymous structs without warning.

(That enables what it considers "Microsoft extensions")

You can also achieve the same effect in valid C++ using this convention.

union Byte
{
  struct bits_type {
    unsigned int _0: 1;
    unsigned int _1: 1;
    unsigned int _2: 1;
    unsigned int _3: 1;
    unsigned int _4: 1;
    unsigned int _5: 1;
    unsigned int _6: 1;
    unsigned int _7: 1;
  } bit;
  struct nibbles_type {
    unsigned int _0: 4;
    unsigned int _1: 4;
  } nibble;
  unsigned char byte;
};

With this, your non-standard byte.nibble_0 becomes the legal byte.nibble._0



来源:https://stackoverflow.com/questions/16202576/c-anonymous-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!