crestrict-qualifier

restrict qualifier for different types


I undestand the usefullness of restrict in something like

void foo(size_t n, double * restrict a, double * restrict b) 

However, looking into man pages for printf, we have:

      int fprintf(FILE *restrict stream,
                   const char *restrict format, ...);

Both pointers are marked as restricted, however they point to different types, so in my understanding, they can't be aliases anyway (unless FILE is a typedef for char), so restrict doesn't provide any more information.

Am I correct, or the man page shows a valid usage ?


Solution

  • Both pointers are marked as restricted, however they point to different types, so in my understanding, they can't be aliases anyway (unless FILE is a typedef for char), so restrict doesn't provide any more information.

    Am I correct, or the man page shows a valid usage ?

    You are not correct.

    First off, pointer values can be converted to different pointer types, so you cannot assume non-aliasing based on type alone, at least not at the function call interface. The function can, in principle, convert the FILE * to a char * and use the result to access whatever data are pointed to. That doesn't even require violating the strict aliasing rule, but depending on the details, it could violate restrict qualification.

    But a more plausible issue in this area would be if FILE were a structure type (which it typically is), and the second argument to a call to this function pointed to a member of the pointed-to FILE structure. modifications to that member could then violate the restrict qualification.

    Additionally, you are ignoring that fprintf() takes an arbitrary number of additional arguments and that it can, in principle, access external objects. The non-aliasing requirements imposed by restrict are not about pairs of restrict-qualified pointers. They are about individual restrict-qualified pointers relative to any other means at all of modifying objects.

    Lastly, even if we could somehow conclude from the function signature (contrary to actual fact) that no relevant aliasing was possible, that would not make the use of restrict invalid. It would just be superfluous.