考慮這個代碼,VC9不檢測別名:限制-edness與預C99
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 */
最明顯的解決方法是使用一個臨時:
void rotate_cw(vec_t const *from,
vec_t *to)
{
int temp = from->x;
to->x = from->y;
to->y = -temp;
}
這是標準的行爲嗎?我期待編譯器,除非被告知,否則會假設這兩個指針可能會被別名。
是的,這不是標準的行爲 - 看起來像一個編譯器錯誤,至少在C99和C++中。他們明確允許相互混淆。我不知道C89是怎麼回事,這似乎是你的原因:(但我認爲我在C89閱讀,事情更容許 – 2009-06-07 20:04:35
你期待C爲你照顧一個角落案件?它並沒有這樣做:你期望自己擔心這些細節,這可能是考慮更高級語言的一個原因,但它不是* c中的錯誤:編譯器完全是做什麼的你告訴它 – dmckee 2009-06-07 20:24:32