Ansari
Ansari

Reputation: 33

How C compiler interpret this program?

I have following program

struct test
{
int length;
union
{
    struct
    {
        int pid_test;
        int age;
    }_testing1;

    struct
    {
        int pid_test;
        int age;
    }_testing2;
}_un;
};

#define pid_test _un._testing1.pid_test
int main()
{
{
    struct test *pOBJ = (struct test *)malloc( sizeof(struct test) );
    pOBJ->_un._testing2.pid_test = 1;
    free(pOBJ);
}
}

When I run it, it gives me following error

error: ‘struct <anonymous>’ has no member named ‘_un’

When I changed the code in the following way, it works fine.

pOBJ->pid_test = 1;

I don't know how compiler interpret the above mentioned code. Any help would be highly appreciated

Upvotes: 1

Views: 55

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

When you have that pid_test macro defined,

pOBJ->_un._testing2.pid_test

expands to

pOBJ->_un._testing2._un._testing1.pid_test

I'm sure you can spot the problem.

Upvotes: 4

Related Questions