CHRIS
CHRIS

Reputation: 955

Anonymous structs

I need an anonymous struct embedded within struct test so that it is set up like the following:

#include <stdio.h>

struct test {
    char name[20];

    struct {
        int x;
        int y;
    };
};

int main(void) {
    struct test srs = { "1234567890123456789", 0, 0 };
    printf("%d\n", srs.x); // I can access x property without having to go to go within another struct
    return 0;
}

So that I can access x and y properties without having to go to go within another struct.

However I would like to be able to use a struct definition which is declared elsewhere like so:

struct position {
    int x;
    int y;
}

I am not able to edit the above struct!

So, for example, some pseudo code might be:

#include <stdio.h>

struct position {
    int x;
    int y;
};

struct test {
    char name[20];

    struct position;
};

int main(void) {
    struct test srs = { "1234567890123456789", 0, 0 };
    printf("%d\n", srs.x); // I can access x property without having to go to go within another struct
    return 0;
}

However this gives:

warning: declaration does not declare anything
In function 'main':
error: 'struct test' has no member named 'x'

UPDATE: Some commenters are wondering how to initialise such a struct, so I wrote a simple program for you to experiment with, make sure to compile with -fms-extensions as per the answer!

#include <stdio.h>

struct position {
    int x;
    int y;
};

struct test {
    char name[20];

    struct position;
};

int main(void) {
    struct test srs = { "1234567890123456789", 1, 2 };
    printf("%d\n", srs.x);
    return 0;
}

The output is 1, which you would expect.

There is no need for:

struct test srs = { "1234567890123456789", { 1, 2 } };

However if you do, it will give the same output with no warnings.

I hope this clarifies!

Upvotes: 2

Views: 2221

Answers (2)

askmish
askmish

Reputation: 6674

As per c11 standards, its possible to use anonymous structs in gcc. Using -fms-extensions compiler option will allow for anonymous struct features you want.

Relevant excerpt from the docs:

Unless -fms-extensions is used, the unnamed field must be a structure or union definition without a tag (for example, ‘struct { int a; };’). If -fms-extensions is used, the field may also be a definition with a tag such as ‘struct foo { int a; };’, a reference to a previously defined structure or union such as ‘struct foo;’, or a reference to a typedef name for a previously defined structure or union type.

Refer: this page for more information.

Upvotes: 7

David Ranieri
David Ranieri

Reputation: 41017

#define position {int x; int y;}

struct test {
    char name[20];

    struct position;
};

Is expanded to:

struct test {
    char name[20];

    struct {int x; int y;};
};

Upvotes: 1

Related Questions