Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous struct with ANSI C

I want to know if it is possible to declare anonymous structs in ANSI C. The code I have is:

struct A
{
    int x;
};

struct B
{
    struct A;
    int y;
};

When I compile it I get: warning: declaration does not declare anything

I have read that the flag -fms-extensions does the trick, it however only works on windows systems as it produces: warning: anonymous structs are a Microsoft extension [-Wmicrosoft]

Is there any ANSI equivalent extension that I can use?

like image 829
Klas. S Avatar asked Apr 27 '26 07:04

Klas. S


1 Answers

A trick to get almost this feature in ANSI C is to use an appropriate macro:

struct A {
    int x;
};

struct B {
    struct A A_;
    int y;
};

#define bx A_.x

Then you can simply do

struct B foo, *bar;

foo.bx;
bar->bx;

In C11 though, anonymous structures are supported and you can simply do

struct B {
    struct {
        int x;
    };

    int y;
}

but sadly not

struct A {
    int x;
};

struct B
{
    struct A;
    int y;
};

As the anonymous structure has to be declared inside the structure it is anonymous to.

See this answer for more details on anonymous members in C11.

like image 129
fuz Avatar answered May 01 '26 00:05

fuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!