C11 - convert pointer-to-structure for anonymous first member structure

Standard C states:

A pointer to a structure object that is appropriately discarded indicates its initial member (or if this element is a bit field, and then to the block in which it is located) and vice versa.

Is there any possible (and well-defined) way to perform such a “suitable cast” in C11 if the first member of the structure in question is an anonymous structure / union? Or do the inverse transform the other way around if the containing structure is anonymous?

I assume that casting for a non-anonymous structure with the same member sequence as the anonymous structure will make this not entirely certain, since they are incompatible and therefore are not guaranteed to have the same memory layout.

However, the C standard states:

In addition, two structures, a union or enumerated types, declared in separate translation units, are compatible if their tags and elements satisfy the following requirements: if declared by a tag, others must be declared by the same tag. If they are completed anywhere in their respective translation units, then the following additional requirements apply: to be a one-to-one correspondence between their members <...>

Can we try to apply this rule to anonymous structures? Let's say if we have the following setting:

header.h:

struct container {
    struct {
        int a;
        char b;
    };
};

void print(struct container *pcontainer);

sep.c:

#include <stdio.h>
#include "header.h"

void print(struct container *pcontainer){
    printf("%d\n", ((struct { int a; char b; }*)pcontainer)->a);
}

main.c:

#include "header.h"

int main(void){
    struct container container, *pcontainer;

    pcontainer = &container;
    pcontainer->a = 1;

    print(pcontainer);

    return 0;
}

( gcc (GCC) 4.8.3 20140911 1).

, print, , struct container, main.c. ", "? , , - ?

+4
1

:

5.1.1.1

  • C . , ( ) . , #include . .

, c . , sep.c header.h. struct struct { int a; char b; }, struct, - print. .

6.2.7

  • , . 6.7.2 , 6.7.3 6.7.6 . , , , ...

, .

, 6.2.7.

, print(), .

+2

All Articles