
difference between punning and aliasing
Quote:
> >Hi...
> >What's the _conceptual_ difference
> >between punning and aliasing?
[...]
Quote:
> This gives rise to the possibility that a char * reference may be
> an alias for another object. E.g in this function
> void foo(char *p, double *q)
> {
> /*...*/
> }
> the language implementation cannot assume that p and q do not
> refer to aliased objects, but in this function it can:
> int foo(int *p, double *q)
> {
> /*...*/
> }
Are you sure? On a platform where double has the same or stricter
alignment requirements than int (most platforms, I believe), what is
wrong with the following? (Except the obvious limited utility.)
int foo(int *p, double *q) {
unsigned char *puc1 = (unsigned char *)(double *)p;
unsigned char *puc2 = (unsigned char *)q;
if(puc1[0] == puc2[0])
return 1;
else
return 0;
}
double z = 0.;
int i = foo((int *)&z, &z);
As a side note, considering how the function is used in this case, is
the cast to "double *" in foo() necessary? Here is a quote from C99
6.3.2.3:
7 A pointer to an object or incomplete type may be converted to a
pointer to a different object or incomplete type. If the resulting
pointer is not correctly aligned 57) for the pointed-to type, the
behavior is undefined. Otherwise, when converted back again, the
result shall compare equal to the original pointer. When a pointer
to an object is converted to a pointer to a character type, the
result points to the lowest addressed byte of the object.
Should p be considered a valid pointer to an object of type double for
the purpose of the previous sentence (in which case, the cast is not
required)? Or should p be considered a "black box" of some sort, out of
which you can pull a valid double *, but which isn't a valid pointer to
a double object itself, so the words "the result points to the lowest
addressed byte of _the_ object" (which object?) cannot be applied? (In
which case, the cast is required, limiting the use of the function to
pointers to double.)
--
Joe