Restrict关键字

来源:互联网 发布:中国网络诗歌网为什么 编辑:程序博客网 时间:2024/04/29 02:09

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 = 0;    *y = 1;    return 0;}

这是在没有restrict关键字时的表现。现在C99增加了restrict关键字。针对上边的例子,我们可以这样修改,使编译器达到更优的优化效果。

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

此时,由于x是修改*x变量的唯一途径,编译器可以确认“*y=1;”这行代码不能修改*x变量的内容,因此可以安全的优化为:

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

注意

restrict 是C99中定义的关键字,使用gcc编译时,需要使用参数 -std=c99 指定。


转载自“暗恋的滋味”的博客 http://blog.csdn.net/lovekatherine/article/details/1891806

Edit in Markdown by chxnew@163.com

0 0
原创粉丝点击