Here is some code I wrote (using GCC's __restrict__
extension to 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, the C version (in case the C++ version is not clear due to the use of an extension which 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've read, if I do *a = 5
, it changes the value of the memory he, a
, is pointing to; after that, the memory to which he is pointing to should not be modified by anyone else except a
, which means that these programs are wrong because b
and c
modify it after that.
Or, even if b
modifies i
first, after that only a
should have access to that memory (i
).
Am I getting it correctly?
P.S: Restrict in this program doesn't change anything. With or without restrict, the compiler will produce the same assembly code. I wrote this program just to clarify things, it is not a good example of restrict
usage. A good example of restrict
usage you can see here: http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html