Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What might you use a nameless struct or union for?

Tags:

c++

I can see how

union {
uint32_t ip_address
 struct {
          uint8_t oct1;
          uint8_t oct2;
          uint8_t oct3;
          uint8_t oct4;
        };
};

Might be of some use to someone, but struct in a struct example here: Detail of MS warning C4201 seems a bit odd. Can anyone demonstrate a good usage case?

like image 498
Chris Huang-Leaver Avatar asked Jan 07 '11 14:01

Chris Huang-Leaver


1 Answers

A nameless union inside a struct makes sense because it allows you to refer to the members of the union without specifying its name, hence shorter code:

struct {
  int a;

  union {
    int b, c, d;
  };
} foo;

So accessing the members of the union is just like accessing a member of the containing struct: foo.a and foo.b. Otherwise you have to use foo.union_name.b to access a member of the union.

Of course a "user" programmer using such a struct should be aware that setting foo.c affects the value of foo.b and foo.d.

For the same reason the reverse can be done, namely putting an anonymous struct inside a union:

union {
  struct {
    int a, b;
  };

  int c;
} foo;

This way foo.a and foo.b can be used simultaneously and foo.c can be used in another case.

I can't think of any other uses for anonymous structs or unions. "Declaring" an anonymous struct/union is an oxymoron and is just like saying int; instead of int a;.

like image 192
Blagovest Buyukliev Avatar answered Sep 27 '22 20:09

Blagovest Buyukliev