restrict是c99标准引入的,它只可以用于限定和约束指针,表明指针是访问一个数据对象的唯一方式。即它告诉编译器,所有修改该指针所指向内存中内容的操作都必须通过该指针来修改,而不能通过其它指针来修改;这样做的好处是,能帮助编译器进行更好的优化代码,生成更有效率的汇编代码。
#include <stdio.h>
#include <stdlib.h>
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 main(int argc, char *argv[])
{
int n = 0;
f(&n, &n);
printf("n = %d\n", n);
exit(0);
}
在这个例子中,指针pci 和 pi 都指向同一个变量n。你不能通过指针pci来改变n的值,却可以通过指针pi改变n的值。
因此,编译器不允许内存访问*pci来预加载n的值(通过指针pic来获取n的值,这是一种编译器的优化行为)。
在这个例子中,编译器不能预加载n的值,因为n的值在函数f()的执行中被改变了2次(作者说是3次???)。
然而,也有变量只通过一个指针访问的情况,例子如下:
FILE *fopen(const char * filename, const char * mode);
The name of the file and its open mode are accessed through unique pointers in fopen(). Therefore, it's possible to preload the values to which the pointers are bound. Indeed, the C99 standard revised the prototype of the function fopen() to the following:
在函数fopen()中文件名和他的打开方式都是通过独有的指针进行访问的。所以,可以预加载指针限定的值。
在C99标准中将函数fopen()的原型修改成如下方式:
/* new declaration of fopen() in <stdio.h> */
FILE *fopen(const char * restrict filename,
const char * restrict mode);
Similar changes were applied to the entire standard C library: printf(), strcpy() and many other functions now take restrict pointers:
整个C标准库都做了同样的修改,像printf(), strcpy()等许多函数现在都使用restrict型指针:
int printf(const char * restrict format, ...);
char *strcpy(char * restrict s1, const char * restrict s2);
C++ doesn't support restrict yet. However, since many C++ compilers are also C compilers, it's likely that this feature will be added to most C++ compilers too.
C++还不支持关键字restrict 。但是许多C++编译器同时也是C编译器。就像关键字restrict被加入了大部分C++编译器。