Anonymous Union Member Access

  • Thread starter Michael B Allen
  • Start date
M

Michael B Allen

Consider the following structure with a union:

struct shape {
int type;
union {
struct circle c;
struct square s;
struct polydoodle p;
} u;
};

To access the circle member c one would do:

struct circle *c = &sh.u.c;

But is it legit to access union members through the union rather than
through the arm explicitly like:

struct circle *c = &s.u;

?

Mike
 
X

xarax

Michael B Allen said:
Consider the following structure with a union:

struct shape {
int type;
union {
struct circle c;
struct square s;
struct polydoodle p;
} u;
};

To access the circle member c one would do:

struct circle *c = &sh.u.c;

But is it legit to access union members through the union rather than
through the arm explicitly like:

struct circle *c = &s.u;

You'll need a cast, but otherwise it looks alright.
All union members are guaranteed to start at offset
zero.

struct circle *c = (struct circle *) &s.u;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top