Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

c - what is the meaning of restrict in the function signature?

int pthread_create(pthread_t *restrict thread,
              const pthread_attr_t *restrict attr,
              void *(*start_routine)(void*), void *restrict arg);

I would like to know what the meaning of restrict is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's something introduced in C99 which lets the compiler know that the pointer passed in there isn't pointing to the same place as any other pointers in the arguments. If you give this hint to the compiler, it can do some more aggressive optimizations without breaking code.

As an example, consider this function:

int add(int *a, int *b) {

    return *a + *b;
}

Obviously, it adds two numbers from pointers. We can use it like this if we want:

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

Obviously, it will output 8; it's adding 4 to itself. However, if we add restrict to add like so:

int add(int *restrict a, int *restrict b) {
    return *a + *b;
}

Then the previous main is now invalid; it's passing &number as both arguments. You may, however, pass in two pointers pointing to different places.

int main(int argc, char **argv) {
    int numberA=4;
    int numberB=4;
    printf("%d
", add(&numberA, &numberB));
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...