4

Does the following method respect the "restrict" contract?

void fun(int* restrict foo) {
     int* bar = foo + 32;
     for (int i = 0; i < 32; ++i)
         *bar = 0;
}

My guess is no, but I need some clarification.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Jacko
  • 12,665
  • 18
  • 75
  • 126

1 Answers1

6

Yes, it sure respects the contract.

6.7.3 Type qualifiers

8 An object that is accessed through a restrict-qualified pointer has a special association with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer.135) The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).

In short, at the point foo is defined (the function-call), foo is guaranteed by the programmer to be the only way to refer to the objects (if any) it points to.
All other expressions referring to those object must thus be derived from that pointers value (like bar which is set to foo+32).
Breaking faith is, as always in such cases, duly punished by undefined behavior.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Bravo! Excellent explanation. – Jacko Oct 26 '14 at 02:20
  • I don't think there's any requirement that it be the only way to refer to the objects, but rather that (1) the sequencing of reads made via a restrict pointer or copy thereof may be arbitrarily moved back in time as far as the point where the restrict pointer was created; (2) the sequencing of writes made via a restrict pointer or copy thereof may be arbitrarily deferred as long as the original restrict pointer is in scope. If a function receives two `restrict` pointers as parameters, passing the same address to both would be legitimate if no part of an object which is written using one... – supercat Aug 16 '15 at 22:04
  • ...is accessed using the other. – supercat Aug 16 '15 at 22:05