EsteveBlanch
EsteveBlanch

Reputation: 115

Struct->Union-Struct

I have this struct:

struct foo {
   int a;
   union {
      struct {
         int b;
         struct bar
         {
            int c;
            int d;
         } *aBar;
      } in;
   } u;
};

How I need to declare a variable of type bar, in Visual C++ ?

Upvotes: 0

Views: 295

Answers (2)

EsteveBlanch
EsteveBlanch

Reputation: 115

Thanks Ajay, I solved that way:

foo *k;
decltype(k->u.in.aBar) j;
j->c = 1;
j->d = 1;

Upvotes: 0

Ajay
Ajay

Reputation: 18431

When you declare an structure like this:

struct 
{ 
    int b;  
} in;

You are actually creating an object with name in, having unnamed-data type. This data-type would be named internally by compiler, and depends on compiler. The style given above does not declare in to be a type, but a variable!

If you want to make it a type, use either of given approaches:

// Approach 1
struct in{...};

// Approach 2
typedef struct {..} in; // in is now a type, because of `typedef`

If you have compiler that supports C++0x, and specifically type decltype keyword, you can use it against the first style (which makes in a variable). Example:

decltype(in) in_var;
in_var.b = 10;

Upvotes: 1

Related Questions