Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compatible struct types

The C 11 standard defines struct compatibility as follows (6.2.7):

Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If one is declared with a tag, the other shall be declared with the same tag. If both are completed anywhere within their respective translation units, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types…

That means I can have 2 files like this:

foo.c:

struct struc {
    int x;
};

int foo(struct struc *s)
{
    return s->x;
}

main.c:

struct struc {
    float x;
};

int foo(struct struc *s);

int main(void)
{
    return foo(&(struct struc){1.2f});
}

Smells like undefined behavior (as it is for types like int and float). But if I am understanding the standard correctly (maybe I am misinterpreting the second sentence), this is allowed. If so, what is the rationale behind this? Why not also specify that structs in separate translation units must also be structurally equivalent?

like image 237
wingerse Avatar asked Mar 23 '26 11:03

wingerse


1 Answers

Smells like undefined behavior

Because it is.


But if I am understanding the standard correctly

This doesn't seem to be the case in this particular instance.

this is allowed.

Nope. I do not see (and you do not explain) how the standard language could be interpreted this way.

The standard says

If both are completed anywhere within their respective translation units

This condition holds in your your example.

then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types

This requirement is not satisfied, so the types are not compatible.


Why not also specify that structs in separate translation units must also be structurally equivalent?

The standard specifies exactly that. "[o]ne-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types" is precisely the definition of structural equivalence.

like image 134
n. 1.8e9-where's-my-share m. Avatar answered Mar 26 '26 01:03

n. 1.8e9-where's-my-share m.



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!