Why is compatibility between tags and names required for compatibility with struct / union?

The C99 standard has the following language in section 6.2.7.1:

two structures, unions or listed types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If declared by a tag, the other must be declared with the same tag. If both are complete types, then the following additional requirements apply: there must be a one-to-one correspondence between their members so that each pair of the corresponding members is declared with compatible types and such that if one member of the corresponding pair is declared with a name, the other member is declared with by the same name . For two entities, the corresponding members must be declared in the same order. For two structures or associations, the corresponding bit fields must have the same width. For two enumerations, the corresponding members must have the same value. (highlighted by me)

In particular, this rule makes these two struct with the same layout incompatible, because their tags and participant names do not match:

 struct x_type { int x; }; struct y_type { // << Different tag int y; // << Different member name }; 

It is easy to understand why the types of members and the order in which they are declared must be the same. However, it is unclear why the tags and names of the participants must match, even if they do not affect the binary layout of the struct ?

+6
source share
1 answer

The text you are quoting does not speak of types compatible with layouts, it speaks of types of the same type . This rule is how C determines whether two type definitions are valid repeated definitions of the same type.

In your example, you are damn right that x_type and y_type are incompatible because they, of course, do not describe the same type! If they were compatible, this would mean that calling void foo(struct x_type*) with an argument of type struct y_type* would be valid, which, of course, is not the intention.

The text you specify and the next paragraph are the C-equivalent of ODR C ++ and require that the tags and names of the participants are the same, similar to this wording from [basic.def.odr]:

Given such an object named D , defined in several translation units, then

- each definition of D should consist of the same sequence of tokens; and
- in each definition of D corresponding names scanned in accordance with 3.4 must refer to the object defined in definition D , or must refer to the same object after overload resolution (13.3) and after matching, partial type specialization (14.8.3) , [...]

+2
source

All Articles