天天看點

restrict關鍵

http://bdxnote.blog.163.com/blog/static/84442352010017185053/

restrict關鍵字的含義是:限制、限定、嚴格的;

這個關鍵字是C99标準中新增加的;

簡單地說,restrict關鍵字隻用于限定和限制指針;它告訴編譯器,所有修改該指針所指向記憶體中内容的操作,全都必須基于(base on)該指針,即:不存在其它進行修改操作的途徑;換句話說,所有修改該指針所指向記憶體中内容的操作都必須通過該指針來修改,而不能通過其它途徑(其它變量或指針)來修改;這樣做的好處是,能幫助編譯器進行更好的優化代碼,生成更有效率的彙編代碼;

實驗:

int test_restrict(int* x, int* y)

{

  *x = 0;

  *y = 1;

  return *x;

}

很顯然,test_restrict()函數的傳回值是0,除非參數x和y的值相同;可以想象,99%的情況下該函數都會傳回0而不是1;然而編譯器必須保證生成100%正确的代碼,是以,編譯器不能将原有代碼替換成下面的更優版本的代碼:

  return 0;   //<---直接替換成0;

C99标準中新增加了restrict這個關鍵字,關鍵字restrict就可以幫助編譯器安全地進行代碼優化了:

int test_restrict(int* restrict x, int* restrict y)

由于使用restrict關鍵字來修飾參數x了,是以,指針x是修改指針x所指向記憶體中内容的唯一途徑,編譯器可以确認"*y = 1;"這行代碼絕對不會修改*x的内容,是以,編譯器可以安全地把代碼優化為:

注意:關鍵字restrict是C99标準中新增加的關鍵字,C++目前仍未引入;編譯時,可通過在gcc的指令行使用參數"-std=c99"來開啟對C99标準的支援;即:目前C++語言還不支援關鍵字restrict,而C語言支援;是以,restrict關鍵字目前隻能出現在.c檔案中,而不能出現在.cpp檔案中;

實驗一:test_restrict.cpp

#include <stdio.h>

int main(int argc, char** argv)

  int a = -1, b = -2;

  a = test_restrict(&a, &b);

  return a;

此時,編譯報錯:

sxit@sxit-bqm:~/test> gcc -o test test_restrict.cpp -std=c99

cc1plus: warning: command line option "-std=c99" is valid for C/ObjC but not for C++

test_restrict.cpp:3: error: expected ',' or '...' before 'x'

test_restrict.cpp: In function 'int test_restrict(int*)':

test_restrict.cpp:5: error: 'x' was not declared in this scope

test_restrict.cpp:6: error: 'y' was not declared in this scope

test_restrict.cpp: In function 'int main(int, char**)':

test_restrict.cpp:3: error: too many arguments to function 'int test_restrict(int*)'

test_restrict.cpp:13: error: at this point in file

sxit@sxit-bqm:~/test>

報錯了,在Solaris和Suse上報同樣的錯;把test_restrict.cpp重命名為test_restrict.c之後,就可以編譯通過了:

sxit@sxit-bqm:~/test> gcc -o test test_restrict.c -std=c99

繼續閱讀