G
G
GloooM2011-10-31 09:45:16
C++ / C#
GloooM, 2011-10-31 09:45:16

C++: Anonymous structures in union?

In light of the recent articles about changing the C++11 standards, I wanted to ask the following point. I'm not a great C++ expert, I'm still learning. Faced the following problem, the device transmits information about its state in one byte, where each specific bit corresponds to a specific parameter. There are very handy things in C/C++ - union and bit fields.
In theory, for such a task, it should look like this

union Data
{
  struct
  {
    unsigned int param1 :1;
    unsigned int param2 :1;
    unsigned int param3 :1;
    unsigned int param4 :1;
    unsigned int param5 :1;
    unsigned int param6 :1;
    unsigned int param7 :1;
    unsigned int param8 :1;
  } params;
  unsigned char Byte;
};
Data info;

Here it turns out that you can write a byte to and then work with the parameters as But for greater readability of the code, you can also do this.
info.Byte = 0x21;
info.params.param3 = 1;
union Data
{
  struct
  {
    unsigned int param1 :1;
    unsigned int param2 :1;
    unsigned int param3 :1;
    unsigned int param4 :1;
    unsigned int param5 :1;
    unsigned int param6 :1;
    unsigned int param7 :1;
    unsigned int param8 :1;
  };
  unsigned char Byte;
};
Data info;

Then you can write the byte all the same, but you can work with bits in a more understandable and simple way. I like the second option purely aesthetically more, but I have vague doubts about its compliance with the standards. Is it possible to use anonymous structures in such unions? Bourgeois on the forums seem to say that this is not a gut, but at the same time, the same GCC compiles this code without warnings and everything works as it should. Tell me if such a use is possible or is it only a feature of GCC and, accordingly, the compiler-dependent code is obtained?
info.Byte = 0x21;
info.param3 = 1;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gouranga, 2011-10-31
@gouranga

info.Byte = 0x21;
info.param3 = 1;

If you want to write like this, then what was the point of allocating a separate structure for this?
ps And why do you have Byte with a capital letter, and paramX with a small one? Ata-ta you for the style. :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question