Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

c - Why is the format in printf marked as restrict?

I just happened to look at the prototype of the printf (and other fprintf class of functions) -

int printf(const char * restrict format, ...);

The keyword restrict if I understand correctly disallows access to the same object through two pointers if one of them is marked restrict.

An example that cites the same from the C standard is here.

One benefit of marking the format as restrict I think is saving the function from the chance that the format string might get modified during the execution (say because of the %n format specifier).

But does this impose a bigger constraint? Does this make the following function call invalid?

char format[] = "%s";
printf(format, format);

Because there is clearly an aliasing here. Why was the restrict keyword added to the format argument of printf?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

cppreference

During each execution of a block in which a restricted pointer P is declared (typically each execution of a function body in which P is a function parameter), if some object that is accessible through P (directly or indirectly) is modified, by any means, then all accesses to that object (both reads and writes) in that block must occur through P (directly or indirectly), otherwise the behavior is undefined.

(emphasis mine)

It means that:

char format[] = "%s";
printf(format, format);

Is well-defined because printf won't attempt to modify format.

The only thing that restrict makes undefined is 'writing to the format string using %…n while printf is running' (e.g. char f[] = "%hhn"; printf(f, (signed char *)f);).

Why was the restrict keyword added to the format argument of printf?

restrict is essentially a hint the compiler might use to optimize your code better.

Since restrict may or may not make code run faster, but it can never make it slower (assuming the compiler is sane), it should be used always, unless:

  • Using it would cause UB
  • It makes no significant performance improvement in this specific case

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...