How does * restrict / * __ restrict__ work in C / C ++?

Here is the code I wrote (using the GCC __restrict__ extension for C ++):

 #include <iostream> using namespace std; int main(void) { int i = 7; int *__restrict__ a = &i; *a = 5; int *b = &i, *c = &i; *b = 8; *c = 9; cout << **&a << endl; // *a - which prints 9 in this case return 0; } 

Or C version (in case the C ++ version is not clear due to the use of the extension that every popular C ++ compiler supports) using GCC:

 #include <stdio.h> int main(void) { int i = 7; int *restrict a = &i; *a = 5; int *b = &i, *c = &i; *b = 8; *c = 9; printf("%d \n", **&a); // *a - which prints 9 in this case return 0; } 

From what I read, if I do *a = 5 , it changes the value of the memory that it points to, a ; after that, the memory that he points to should not be changed by anyone other than a , which means that these programs are incorrect, because b and c change it after that. Or even if b first changes i , after that only a should have access to this memory ( i ). Did I understand correctly?

PS: The restriction in this program does not change anything. With or without restriction, the compiler will produce the same assembly code. I wrote this program to clarify the situation, this is not a good example of using restrict . You can see a good example of using restrict here: http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html

+7
source share
1 answer

Not.

reports

 *b = 8; *c = 9; 

will result in undefined behavior.

From the documentation:

A pointer is the address of a place in memory. More than one pointer can access the same memory fragment and change it during the program. A qualifier of type restrict is an indicator for the compiler, which, if the memory addressed to restrict -qualified pointer is changed, no other pointer will gain access to the same memory. The compiler may choose to optimize the code with restrict -qualified pointers so that otherwise it could lead to incorrect behavior. It is the programmer's responsibility to use restrict -qualified pointers, as they were intended to be used. Otherwise, undefined behavior may occur.

+11
source

All Articles