• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 512
  • Last Modified:

unions & structs

Can we have anonymous unions and structs in the C programming language.
1 Solution
union - yes. struct - no.
Actually, you can have both, but they are messy and rarely used. Examples:

struct {int x, y} myPoint;
union {char a; int i} intOrChar;

myPoint.x = 4;
myPoint.y = 6; // coordinate of (4,6)

intOrChar.i = 7; // intOrChar is treated as an int == 7
intOrChar.a = 'a'; // intOrChar is treated as a char == 'a'
//note intOrChar.i is garbage once you use intOrChar.a

the names of the union and struct are anonymous. Hope this helps.
Yonat is right.  However:

"A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name. These nested structures are called anonymous structures. C++ does not allow anonymous structures."

Other compilers may support this non-standard feature as well.
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

apmontgo is wrong :-(
apmontgo, an anonymous struct would be a struct without *any* name, even that of a struct variable. Here is an example of an anonymous union:

struct external {
    union {
        int n;
        float x;
} var;

var.n = 7;
var.x = 3.14;

Get it?
Funny, an incorrect answer was accepted.
tausifafAuthor Commented:
I had not accepted the answer that you guys had proposed. I got the answer from a friend of mine. Anyway, I did not wanted to pursue the discussion further. Thanks for the feedback.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Live webcast with Pinal Dave

Pinal Dave will teach you tricks to help identify the real root cause of database problems rather than red herrings. Attendees will learn scripts that they can use in their environment to immediately figure out their performance Blame Shifters and fix them quickly.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now