爲了幫助編譯器肯定存儲器相關性,能夠使用關鍵字restrict來限定指針、引用或數組。關鍵字restrict是對指針、引用或數組的一種限定。使用restrict關鍵字是爲了確保其限定的指針在聲明的範圍內,是指向一個特定對象的惟一指針,及這個指針不會和其它指針指向存儲器的同一地址。這使編譯器更容易肯定是否有別名信息,從而更好地優化代碼。
下例中,關鍵字restrict的使用告知編譯器func1中指針a和b所指向的存儲器範圍不會交疊,這代表經過指針變量a和b對存儲器的訪問不會衝突,即對一個指針變量的寫操做不會影響另外一個指針變量的讀操做。
void func1(int * restrict a, int * restrict b)
{
/* func1’s code here */
}數組
To help the compiler determine memory dependencies, you can qualify a pointer, reference, or array with the restrict keyword. The restrict keyword is a type qualifier that may be applied to pointers, references, and arrays. Its use represents a guarantee by the programmer that within the scope of the pointer declaration the object pointed to can be accessed only by that pointer. Any violation of this guarantee renders the program undefined. This practice helps the compiler optimize certain sections of code because aliasing information can be more easily determined.app
In the example that follows, the restrict keyword is used to tell the compiler that the function func1 is never called with the pointers a and b pointing to objects that overlap in memory. You are promising that accesses through a and b will never conflict; this means that a write through one pointer cannot affect a read from any other pointer. The precise semantics of the restrict keyword are described in the 1999 version of the ISO C standard.優化
Use of the restrict type qualifier with pointersthis
void func1(int * restrict a, int * restrict b)
{
/* func1’s code here */
}指針
This example illustrates using the restrict keyword when passing arrays to a function. Here, the arrays c and d should not overlap, nor should c and d point to the same array.
Use of the restrict type qualifier with arraysrest
void func2(int c[restrict], int d[restrict])
{
int i;
for(i = 0; i < 64; i++)
{
c[i] += d[i];
d[i] += 1;
}
}code
下面的文字來自flybird:orm
關鍵字restrict的使用能夠經過下面兩個程序來講明 。
以下程序:兩個均完成2個16位短型數據數組的矢量和對象
程序1:blog
void vecsum( short *sum, short *in1, short *in2, unsigned int N)
{
int i;
for(i=0;i<N;i++)
sum[i]=in1[i]+in2[i];
}
程序2:
void vecsum(short * restrict sum, restrict short * in1, restrict short * in2,unsigned int N)
{
int i;
for (i=0;i<N;i++)
sum[i]=in1[i]+in2[i];
}
編譯器在編譯程序1時,沒法判斷指針*sum與指針*in1,*in2是否獨立。此時,編譯器採起保守的辦法,認爲他們是相關的,即:認爲*sum指向的存儲區與*in1,in2指向的存儲區可能混迭。這時編譯出的代碼必須執行完前一次寫,而後才能開始下一次讀取。在編譯程序2的時候restrict代表指針*in1,*in2是獨立的,*sum不會指向他們的存儲區,於是能夠並行進行多個數據的讀取與求和。這兩種程序編譯出的代碼執行速度相差極大。