Introduction: in kernel system calling functions, we often encounter the condition that function parameters are restricted by the restrict clause. Below we will summarize this keyword.
1. The restrict keyword is added only when the C99 feature is used. Therefore, when compiling a program containing the qualified word, you must add the-std = c99 flag behind it, this enables gcc to support the c99 standard.
2. Since restrict is a qualified word, what variables does it limit? It can only limit pointer variables! The data object defined by it indicates the unique and initial method for accessing the data object when the pointer is used. Note: the unique here indicates that the data block pointed to by the pointer defined by it can only be accessed by this pointer, and cannot be accessed in any way other than it. Initially, it must be declared at initialization and cannot be declared later. The following is an example.
3. restrict can be viewed as only two readers. One is the compiler, which tells the compiler to freely make optimization assumptions. Another reader is the user, which tells the user to apply only the parameters that meet the restrict requirements. For example, the following two function declarations:
Void * memcpy (void * restrict s1, const void * restrict s2, size_t n );
Void * memmove (void * s1, const void * s2, size_t n );
Both of the above functions copy n Bytes from position s2 to position s1. The memcpy () function requires no overlap between two locations, but memmove () does not. Declaring s1 and s2 as restrict means that each pointer is the only way to access the corresponding data, so they cannot access the same data block. This satisfies the non-overlapping requirements.
Program example restrict. c:
# Include <stdio. h> # include <stdlib. h> intmain (int argc, char ** argv) {int n; int ar [5]; int * restrict restar = (int *) malloc (5 * sizeof (int);/* declare the pointer to restrict, so that the data in this memory can only be accessed by restar, cannot be accessed by the following par pointer */int * par = ar; for (n = 0; n <5; n ++) {par [n] + = 5; restar [n] + = 5; ar [n] * = 2; par [n] + = 3; restar [n] + = 3; printf ("ar [% d] = % d \ n", n, restar [n]); printf ("ar [% d] = % d \ n", n, ar [n]);} return-1 ;}
Compile: gcc restrict. c-std = c99
Execute the compilation result:./a. out
Ar [0] = 8
Ar [0] = 4851221
Ar [1] = 8
Ar [1] = 4849653
Ar [2] = 8
Ar [2] = 269027981
Ar [3] = 8
Ar [3] = 2147391485
Ar [4] = 8
Ar [4] = 2614935
The results show that the data directed by the par pointer and the restar pointer accessed by ar does not play any role. Only restar [n] + = 5; and resrecognition [n] + = 3; statements that can change the data pointing to the memory. In fact, the compiler will optimize these two statements and merge them into one statement: restar [n] + = 8;