Re: Why is C Standard Code Example Invalid?



James Kuyper <jameskuyper@xxxxxxxxxxx> wrote:

The standard is quite clear on this: 6.5.2.3p5 says "... it is permitted
to inspect the common initial part of any of them anywhere that a
declaration of the complete type of the union is visible. ...". Since
the function body of f() is not such a location, it is not permitted.

The question of why it imposes such a requirement is far less clear to
me. There's probably a good reason, but quite frankly, I can't imagine
any way to implement structures and unions where this would cause a
problems.

Let's look at the significant part of the code in question:

int f(struct t1 * p1, struct t2 * p2)
{
if (p1->m < 0)
p2->m = -p2->m;
return p1->m;
}

Since p1 and p2 are pointing to incompatible structs and there's no
visible union that contains them both, the compiler is at liberty to
assume that changes to the struct pointed to by p2 have no affect on the
struct pointed to by p1. Thus, a reasonable code generation strategy
would be to load the value of p1->m into a register as part of the "if"
test, and then use the value in the register for the "return" rather
than re-fetching it from memory. When the structs pointed to by p1 and
p2 are, in fact, members of a (non-visible) union, that produces the
wrong answer. The C Standard says this a bug in the program rather than
a bug in the compiler.

-Larry Jones

What this games needs are negotiated settlements. -- Calvin
.



Relevant Pages

  • Re: Returning a struct from a function - strange behavior
    ... preliminary draft for a future C1x standard. ... the struct or union is already too big to fit ... | course the compiler is still free to do the equivalent of storing it ... there isn't any need for added inefficiencies ...
    (comp.lang.c)
  • Re: union of structs: common variable stored in same address?
    ... The code using this union often looks like ... What Alan said -- all members of a union are aligned at the ... the wording in the standard is watertight. ... "how I think the committee expects ...
    (comp.lang.c)
  • Re: Copying from one struct to another, simple assignment?
    ... entire union. ... Once you change to .something the compiler knows the ... I can't get that from the standard. ... [assuming .i is int and .c is char] ...
    (comp.lang.c)
  • Re: Youre appointed as Portability Advisor
    ... You're sitting there 100% aware that the Standard explicitly forbids you ... to write to member A of a union and then read from member B, ... compiler vendors' while to listen? ... some of the world's best C programmers. ...
    (comp.lang.c)
  • Re: Overflow Underflow
    ... You must read the union member that was last assigned. ... representation in signed and unsigned. ... but in practice its only UB because the standard ... In theory a compiler could diagnose the ...
    (comp.lang.cpp)