天天看點

Restrict關鍵字C99 Restrict關鍵字

C99 Restrict關鍵字

英文解釋

One of the new features in the recently approved C standard C99, is the restrict pointer qualifier. This qualifier can be applied to a data pointer to indicate that, during the scope of that pointer declaration, all data accessed through it will be accessed only through that pointer but not through any other pointer.

The ‘restrict’ keyword thus enables the compiler to perform certain optimizations based on the premise that a given object cannot be changed through another pointer.

Now you’re probably asking yourself, “doesn’t const already guarantee that?” No, it doesn’t. The qualifier const ensures that a variable cannot be changed through a particular pointer. However, it’s still possible to change the variable through a different pointer.

中文解釋

概括的說,關鍵字restrict隻用于限定指針;該關鍵字用于告知編譯器,所有修改該指針所指向内容的操作全部都是基于(base on)該指針的,即不存在其它進行修改操作的途徑;這樣的後果是幫助編譯器進行更好的代碼優化,生成更有效率的彙編代碼。

例子

int foo(int *x, int *y)
{
    *x = 0;
    *y = 1;
    return 0;
}
           

可以想象在99%的情況下,該函數的傳回值都是0而不是1。在x=y的情況下,這也就是那1%的情況,傳回值為1。編譯器不會将原有的代碼優化為以下版本:

int foo(int *x, int *y)
{
    *x = ;
    *y = ;

    return ;
}
           

這是在沒有restrict關鍵字時的表現。現在C99增加了restrict關鍵字。針對上邊的例子,我們可以這樣修改,使編譯器達到更優的優化效果。

int foo(int *restrict x, int *restrict y)
{
    *x = ;
    *y = ;

    return *x;
}
           

此時,由于x是修改*x變量的唯一途徑,編譯器可以确認“*y=1;”這行代碼不能修改*x變量的内容,是以可以安全的優化為:

int foo(int *restrict x, int *restrict y)
{
    *x = ;
    *y = ;

    return ;
}
           

注意

restrict 是C99中定義的關鍵字,使用gcc編譯時,需要使用參數 -std=c99 指定。

轉載自“暗戀的滋味”的部落格 http://blog.csdn.net/lovekatherine/article/details/1891806

Edit in Markdown by [email protected]