0

So my understanding is that the C99 standard mandates that pointers to different types should not be aliased (i.e. pointed to the same memory). The restrict keyword assures the compiler that two certain variables (of the same type?) are not located in the same memory slot.

Therefore, is it true, that the following function would not profit form the restrict keyword?

void sphere_intersect(float* t, const sphere* s, const ray* r); 

But, a function like this would:

void vector_add(vector* v, const vector* u);
Daniel Lovasko
  • 471
  • 2
  • 10
  • Even pointers to same data types are `restrict`ed. See strcpy for example. – Unmanned Player Aug 29 '17 at 22:41
  • In fact, the only point of `restrict` is to tell compiler that the pointers are different and should not be aliased. Doesn't matter what types are being used. – Unmanned Player Aug 29 '17 at 22:45
  • @UnmannedPlayer isn't it already assumed by the compiler (if you compile with `-fstrict-aliasing`) that pointers to different types are not aliased? Therefore the restrict keyword would only make sense to help the compiler with same types. – Daniel Lovasko Aug 29 '17 at 23:54
  • If any of the pointers is a pointer to character data, the aliasing rules don't apply but `restrict` helps the compiler know that separate pointers point to separate data. – Jonathan Leffler Aug 30 '17 at 00:18
  • "_pointers to different types are not aliased_" No, it's more complicated, and in the end, nobody agrees on what "no aliasing" really means; except in clear type pun were you write `int` then read a `float` at the same location. – curiousguy Sep 06 '17 at 15:04

1 Answers1

1

A function like

void sphere_intersect(float* t, const sphere* s, const ray* r);

could benefit from adding restrict if the types sphere and/or ray contain any float fields. Absent restrict, the compiler must assume that t might alias with any float field in the objects pointed at by s or r. So any write to *t might modify such a field meaning that the compiler could not hold the value of said field in a register for later reuse, but would instead have to reload it.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • I think this answer is the one that should be accepted. Perhaps a follow-up question though: let's assume that there is no `float* t` in that function, only `sphere* s` and `ray* r`. They both contain only float fields - is it still worth adding the `restrict` qualifier please? – Daniel Lovasko Aug 30 '17 at 16:56