about qualifier "restrict"

来源:互联网 发布:pc3000数据恢复 编辑:程序博客网 时间:2024/06/03 20:40

about qualifier "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. For example:

 

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);

pci和pi指向的都是n,虽然pci被const修饰,但pci指向的内容却在函数中被改变了,当用restrict修饰符之后 void f ( const int * restrict pci , int * restrict pi ),问题解决了:一旦我们再有如:f ( &n , &n ) 的调用,编译器将给出错误提示,这是由于一个地址可以通过两个指针来访问

 

Note: The qualifier "restrict" isn't support by C89 or C++, If can't conpliar, please add "-std = C99"