Mike said:
Is the following legal in C99?
Does it violate strict aliasing?
int func(int arg)
{
union {
int i;
char c[sizeof(int)];
} u;
u.i=arg;
scribble(u.c);
return u.i;
}
I've found hints that it is,
but nothing I'm sure of.
It's fine, at least as far as the part that seems to be bothering you is
concerned (the aliasing). One weird machines, scribble(u.c) can produce
a trap representation in u.i, but presumably you are doing this
Are trap ints really allowed in C?
*because* you want to fiddle with the representation and you know what
you are doing. It might be worth saying what your top-level goal is:
i.e. to what problem is the above union a solution? There may be other
well-known solutions.
I know of another solution, but avr-gcc produces awful code for it.
The code I've given is fairly standard procedure for manipulating the
bytes of an int.
It pretty much always works.
I'm trying to discover what C99 actually requires of such code.
If it's undefined behavior, updating a compiler could cause it to fail
without warning.
If it's unspecified behavior, then if it works once,
I would expect it to continue work until a change in the
representation of an int.
As a bonus, the compiler wouldn't complain about it.
Elsewhere in this thread (with so much quoted text that I stopped
reading it) I saw you bring up the issues of using an array of floats
instead of chars. Maybe you could say, here, why you want to do that
since it seems like quite another kind of use for a union. Again,
aliasing is not so much the problem as messing about with complex
representations.
I don't want to use floats.
It was just an example for which I knew the answer and demonstrated my
reason for concern.
In the float example, if scribble changed u.c,
the compiler would be allowed to return 0 or drown my brother-in-law
in nasal demons.
In some situations, chars are a special case,
but I'm unclear on what situations those are.