4

The prototype of printf, according to my stdio.h, is

extern int printf (const char *__restrict __format, ...);

On the page explaining Restrict, it says that it is a keyword used to indicate that pointers are unique. However, I don't understand why one would need that for printf.

Why does printf have a "restrict" keyword?

If it's necessary to explain further what "restrict" means, please do.

extremeaxe5
  • 723
  • 3
  • 13

1 Answers1

1

Basically, the format string shouldn't overlap with any of its arguments or the results are undefined. The restrict makes that clear beyond just mentioning it the documentation.

As for why...

In the case of snprintf() and sprintf() it should be obvious why the format shouldn't overlap with especially the destination buffer, but it's a bit murkier for the variations that output to a file.

I suspect it's because of the %hhn specifier, which sets its argument, a signed char *, to the number of characters written so far. If you pass a pointer to an element of the format string, this would modify the string and thus possibly introduce undefined behavior - what if the number corresponds to the value of the character '%'?

Shawn
  • 47,241
  • 3
  • 26
  • 60