为什么printf中的格式被标记为restrict? [英] Why is the format in printf marked as restrict?
问题描述
刚好看到了的原型printf
(和其他 fprintf
类函数) -
I just happened to look at the prototype of the printf
(and other fprintf
class of functions) -
int printf(const char * restrict format, ...);
关键字restrict
(如果我理解正确的话)不允许通过两个指针访问同一个对象,如果其中一个被标记为restrict
.
The keyword restrict
if I understand correctly disallows access to the same object through two pointers if one of them is marked restrict
.
引用 C 标准中相同内容的示例是 此处.
An example that cites the same from the C standard is here.
我认为将格式标记为 restrict
的一个好处是可以避免在执行过程中格式字符串被修改的可能性(比如因为 %n
格式说明符).
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);
因为这里显然存在别名.为什么要在 printf
的 format
参数中添加 restrict
关键字?
Because there is clearly an aliasing here. Why was the restrict
keyword added to the format
argument of printf
?
推荐答案
cppreference
在声明了受限指针
P
的块的每次执行期间(通常是每次执行一个函数体,其中P
是一个函数参数),如果某个可通过P
(直接或间接)访问的对象被修改,以任何方式,则对该对象的所有访问strong>(读取和写入)在该块中必须通过P
(直接或间接)发生,否则行为未定义.
cppreference
During each execution of a block in which a restricted pointer
P
is declared (typically each execution of a function body in whichP
is a function parameter), if some object that is accessible throughP
(directly or indirectly) is modified, by any means, then all accesses to that object (both reads and writes) in that block must occur throughP
(directly or indirectly), otherwise the behavior is undefined.
(强调我的)
这意味着:
char format[] = "%s";
printf(format, format);
定义良好,因为printf
不会尝试修改format
.
Is well-defined because printf
won't attempt to modify format
.
restrict
唯一使未定义的事情是在 printf
运行时使用 %…n
写入格式字符串"(例如 char f[] = "%hhn"; printf(f, (signed char *)f);
).
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);
).
为什么要在 printf
的格式参数中添加 restrict
关键字?
Why was the
restrict
keyword added to the format argument ofprintf
?
restrict
本质上是编译器可能用来更好地优化代码的提示.
restrict
is essentially a hint the compiler might use to optimize your code better.
因为 restrict
可能会也可能不会使代码运行得更快,但它永远不会使它变慢(假设编译器是健全的),所以应该总是使用它,除非:
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:
- 使用它会导致 UB
- 在这种特定情况下没有显着的性能提升
这篇关于为什么printf中的格式被标记为restrict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!