gpt4 book ai didi

c - 限制关键字 - 优化和别名影响

转载 作者:太空狗 更新时间:2023-10-29 14:50:26 24 4
gpt4 key购买 nike

我在 C11 标准中看到了这两个部分,它们指的是 restrict 限定符:

1#

6.7.3-8

An object that is accessed through a restrict-qualified pointer has a special association with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer.135) The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).

你能解释一下草书片段的意思吗?在我的解释中,因为它没有改变它的意思,所以看起来 restrict 的使用是毫无意义的......

2#

6.7.3.1-6

A translator is free to ignore any or all aliasing implications of uses of restrict.

这些别名可能意味着什么?你能给我举一些例子吗?

最佳答案

Restrict 并非毫无意义,它允许编译器进行优化,如果可能存在指针别名,则不允许进行优化。例如下面的函数:

int foo(int *a, int *b)
{
*a = 5;
*b = 6;
return (*a + *b);
}

这个函数返回什么?如果您说 11,那么您只说对了一部分。它返回 11 除非 a == b,在这种情况下它返回 12,或者更糟的是,a 与 b 部分重叠,这可能是以下之一几个值。为了确保它的行为正确,编译器必须发出代码

1) stores 5 to a
2) stores 6 to b
3) loads a into a temporary register
4) adds the temp and 6
5) returns the sum

如果您作为程序员知道 a == b 永远不会发生,您可以使用 restrict 关键字告诉编译器您不希望它担心这种情况。

int foo(int * restrict a, int * restrict b)

将为该函数生成的代码将是:

1) store 5 to a
2) store 6 to b
3) return 11

编译器能够进行优化,因为您向它保证不会出现别名问题。而且,根据标准,如果编译器只是选择忽略 restrict 关键字,那么它生成的代码将只是第一种情况下的符合(未优化)代码,对于您关心的所有实例,它仍然以相同的方式工作。

关于c - 限制关键字 - 优化和别名影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12220706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com