Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why may there be a difference between union* and struct*?

The C standard mandates that all pointers to unions have the same representation and alignment requirements.
It mandates the same for all pointers to structs.

Thus my question:
Why does the standard not mandate that pointers to unions have the same representation and alignment requirements as pointers to structs? (I would very much appreciate an example of an implementation taking advantage of this.)
Or did I simply miss the relevant text?

The relevant quote from the draft standard n1570 (C11 final draft):

6.2.5 Types § 28

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

like image 480
Deduplicator Avatar asked Jun 19 '14 18:06

Deduplicator


1 Answers

Neither the 1989 ANSI C Rationale nor the ISO C99 Rationale discusses this.

I doubt that there's any strong reason for the lack of such a requirement. Probably the committee didn't want to impose unnecessarily strict requirements. I also doubt that there are any real-world implementations where pointers to structs and pointers to unions don't have the same representations.

Consider, for example, that a struct can contain a single union member, and vice versa, so there's probably no good reason for an implementation to use different representations -- nor is there any good reason for the standard to require all implementations to use identical representations.

The reason all struct pointers "smell alike" is to permit the use of pointers to incomplete types. For example:

struct foo;

void func(struct foo *param);

struct foo { /* member declarations */ };

The compiler doesn't have to know anything about struct foo other than that it's a struct type to know how to generate a call to func().

The same applies to incomplete union types. But an incomplete struct type cannot be completed as a union, or vice versa, so there's no great benefit in being able to assume that they have the same representation.

like image 101
Keith Thompson Avatar answered Sep 25 '22 16:09

Keith Thompson