I’m a little confused about the rules regarding restricted pointers. Maybe someone out there can help me out.
-
Is it legal to define nested restricted pointers as follows:
int* restrict a; int* restrict b; a = malloc(sizeof(int)); // b = a; <-- assignment here is illegal, needs to happen in child block // *b = rand(); while(1) { b = a; // Is this legal? Assuming 'b' is not modified outside the while() block *b = rand(); } -
Is it legal to derive a restricted pointer value as follows:
int* restrict c; int* restrict d; c = malloc(sizeof(int*)*101); d = c; for(int i = 0; i < 100; i++) { *d = i; d++; } c = d; // c is now set to the 101 element, is this legal assuming d isn't accessed? *c = rand();
Thanks!
Andrew
For reference, here’s the
restrictqualifier’s rather convoluted definition (from C99 6.7.3.1 “Formal definition of restrict”):My reading of the above means that in your first question,
acannot be assigned tob, even inside a “child” block – the result is undefined. Such an assignment could be made ifbwere declared in that ‘sub-block’, but sincebis declared at the same scope asa, the assignment cannot be made.For question 2, the assignments between
canddalso result in undefined behavior (in both cases).The relevant bit from the standard (for both questions) is:
Since the restricted pointers are associated with the same block, it’s not possible for block B2 to begin before the execution of B, or for B2 to end prior to the assignment (since B and B2 are the same block).
The standard gives an example that makes this pretty clear (I think – the clarity of the
restrictdefinition’s 4 short paragraphs is on par with C++’s name resolution rules):