在函数签名中限制是什么意思?

q09*_*987 25 c linux multithreading ubuntu-10.04

int pthread_create(pthread_t *restrict thread,
              const pthread_attr_t *restrict attr,
              void *(*start_routine)(void*), void *restrict arg);
Run Code Online (Sandbox Code Playgroud)

我想知道限制的含义是什么?

ick*_*fay 34

这是在C99中引入的东西,它让编译器知道在那里传递的指针没有指向与参数中任何其他指针相同的位置.如果您将此提示提供给编译器,它可以在不破坏代码的情况下进行更积极的优化.

例如,考虑这个功能:

int add(int *a, int *b) {
    return *a + *b;
}
Run Code Online (Sandbox Code Playgroud)

显然,它从指针中添加了两个数字.如果我们想要,我们可以像这样使用它:

// includes excluded for brevity
int main(int argc, char **argv) {
    int number=4;
    printf("%d\n", add(&number, &number));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

显然,它会输出8; 它为自己增加了4个.但是,如果我们添加restrictadd像这样:

int add(int *restrict a, int *restrict b) {
    return *a + *b;
}
Run Code Online (Sandbox Code Playgroud)

那么前一个main现在无效了; 它&number作为两个论点传递.但是,您可以通过指向不同位置的两个指针.

int main(int argc, char **argv) {
    int numberA=4;
    int numberB=4;
    printf("%d\n", add(&numberA, &numberB));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 有关如何有益的信息,请参阅[维基百科页面](http://en.wikipedia.org/wiki/Restrict). (8认同)