<转载>restrict关键词(编译器优化)

restrict:

restrict只适用于指针,它声明一个指针是唯一初始化访问一个数据对象。

int ar[10];
int* restrict restar=(int *)malloc(10*sizeof(int));
int* par=ar;

for(int n=0; n<10; n++) {
par[n]+=5;
restar[n]+=5;
ar[n]*=2;
par[n]+=3;
restar[n]+=3;
}
restar指针是restrict类型,par指针就不是,因为par即没有初始化也不是唯一访问ar数组的变量。
那么,上面的程序,因为restar是唯一反问数据块的指针,所以编译器可以对它优化为一条语句,
restar[n] += 8;     /* ok replacement */
而par就不可以,
par[n] += 8;      / * gives wrong answer */

restrict主要修饰函数的指针参数,或者指向由malloc()分配的内存变量。

restrict不仅仅可以被用来加强编译器的优化,还是解决我们代码中存在的隐患,看下面这个例子:

void f (const int* pci, int *pi;); // is *pci immutable?
{

(*pi)+=1; // not necessarily: n is incremented by 1
*pi = (*pci) + 2; // n is incremented by 2
}

int n;
f( &n, &n);

f( &n, &n);如果对两个参数都使用了restrict关键字,那么这里编译时会报错,因为一个地址可以通过两个指针访问了

但要注意:restrict是C99中新增的关键字,在C89和C++中都不支持,在gcc中可以通过—std=c99来得到对它的支持。



posted @ 2011-10-18 21:06  lq0729  阅读(250)  评论(0编辑  收藏  举报