问题
I recently came across this comment by @Paul Ogilvie:
"You say "To define a pointer to a structure you only need to know the structure tag". In my experience that is unnecessary. Just declare a pointer_to_some_type and the compiler will reserve space for a pointer and does type checking on assignment. Only once you want dereference the pointer and access its members, must the type fully be known."
I tried it out with:
struct foo {
int a;
struct bar* x;
};
struct bar {
int b;
};
and indeed neither GCC nor Clang doesn't throw any diagnostic, as opposed to attempt to defining an object of the respective struct without forward-declaration.
Evidence
But that makes me wonder: Is this standard-compliant?
Citations from the standard are highly appreciated.
回答1:
If the representations are the same, that implies that the sizes are the same.
Section 6.2.6.1p2 of the C standard states:
Values stored in non-bit-field objects of any other object type [ed. not unsigned char] consist of
n×CHAR_BIT
bits, where n is the size of an object of that type, in bytes. The value may be copied into an object of typeunsigned char [n]
(e.g., bymemcpy
); the resulting set of bytes is called the object representation of the value. Values stored in bit-fields consist of m bits, where m is the size specified for the bit-field. The object representation is the set of m bits the bit-field comprises in the addressable storage unit holding it. Tw o values (other than NaNs) with the same object representation compare equal, but values that compare equal may have different object representations.
As an example, an int
and a short
under gcc both use two's complement but they don't have the same object representation because one is 4 bytes and the other is 2 bytes.
来源:https://stackoverflow.com/questions/62840349/is-the-omission-of-a-forward-declaration-for-a-pointer-to-a-structure-valid