Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ anonymous structs

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?

like image 818
Dejwi Avatar asked Apr 24 '13 21:04

Dejwi


People also ask

Can you define a structure without a name?

Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions. Definition is just like that of a normal union just without a name or tag.

What is the difference between union and anonymous union?

An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared.

Is nested unions possible in C?

This is how we can make a nested structure. There is a another way of defining nested union but method accessing and initialization of members will remain same. Let's see the another method of defining nested union. We will define the same union student by another method.

What are nested structures in C?

A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.


1 Answers

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

(That option 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

like image 98
Drew Dormann Avatar answered Oct 28 '22 19:10

Drew Dormann