views:

182

answers:

2

Considering this code, VC9 doesn't detect aliasing :

typedef struct { int x, y; } vec_t;

void rotate_cw(vec_t const *from,
               vec_t       *to)
{
        /* Notice x depends on y and vice versa */
        to->x = from->y;
        to->y = -from->x;
}

/* ... */
vec_t a, b;
rotate_cw(&a, &b); /* OK, no aliasing */
rotate_cw(&a, &a); /* FAIL, aliasing is not detected */

The obvious fix is to use a temporary :

void rotate_cw(vec_t const *from,
               vec_t       *to)
{
        int temp = from->x;
        to->x = from->y;
        to->y = -temp;
}

Is this standard behavior ? I was expecting that the compiler, unless told so, would assume both pointers to be possibly aliased.

+4  A: 

Check out this answer.

Try putting __restrict before the parameters, seems to be the only way anybody found of getting MSVC to give any warnings.

GMan
Thanks for the link. I'd rather need a __norestrict keyword so the compiler doesn't assume restrict-edness.
You can call me Chuck
+3  A: 

The code as written is perfectly valid, in C89 or C99. It is obscure, but there is nothing for the compiler to diagnose, so it doesn't diagnose.

If you used C99 and 'restrict' on both parameters of the function, then you would get an error - if your compiler supports C99. AFAIK, no current version of MSVC yet supports C99 fully.

Jonathan Leffler