2015-04-28 42 views
1

我正在使用mingw32-gcc和C99標準。我通過關於restrict關鍵字http://wr.informatik.uni-hamburg.de/_media/teaching/wintersemester_2013_2014/epc-1314-fasselt-c-keywords-report.pdf的文章進行了一些編輯,從而在代碼下面粘貼了代碼。根據作者,"Result One""Result Two"應該是不同的,但是當我運行它時,它們是相同的。我沒有收到任何編譯器警告。有沒有我錯過的設置?restrict-Keyword無法正常工作?

#include <stdio.h> 

void update(int* a, int* b, int* c) 
{ 
    *a += *c; 
    *b += *c; 
} 

void update_restrict(int* a, int* b, int* restrict c) 
{ 
    printf("*c = %d\n",*c); 
    *a += *c; 
    printf("\n*c = %d - ",*c); 
    printf("shouldn't this have stayed the same?\n\n"); 
    *b += *c; 
} 

int main() 
{ 
    int a = 1, b = 2; 

    update(&a, &b, &a); 

    printf("Result One: a, b = %d, %d\n", a, b); 

    a = 1; b = 2; // reset values 

    update_restrict(&a, &b, &a); 
    printf("Result Two: a, b = %d, %d\n", a, b); 
    getchar(); 
    return 0; 
} 
+2

'restrict'不必影響你的輸出。只有編譯器才能進行可能的優化。結果可能相同,並可能不同。 – cshu

+0

我認爲'update_restrict'中的* c值會在* a發生變化後保持不變,因爲它只會被加載一次。我不明白這是如何影響結果的。 –

+1

你沒有說你是如何編譯的(編譯器版本,命令行標誌等)。 Gcc對restrict的含義有一個弱解釋:標記單個變量restrict對於gcc來說本質上是無用的,它只假設**兩個** restrict的兩個變量不是別名。另外,編譯器可以很好地內聯函數,這可能會使問題消失。在update_restrict上使用__attribute __((noinline,noclone))來避免這種情況。 –

回答

1

About the usage of restrict

從wikipedia.org:

如有合作意向的聲明不被遵守,對象是 由一個獨立的指針訪問,這會導致不確定的 行爲。

此行update_restrict(&a, &b, &a);導致未定義行爲

結果可能相同,也可能不一樣。