restrict 的大多数定义都表示程序员向编译器 promise 在指针的生命周期内,指针是访问对象的唯一方式。这允许编译器优化输出,因为它知道它只能由一个指针访问,因此只能由它更改。如果我理解正确,这通常意味着程序不必重新加载指针指向的值。
如果这是正确的,那么当 restrict 关键字应该可用时应该有一些异常(exception),即使它违背了应该如何使用它的意图。
想到的一件事是指针指向的数据在指针的生命周期内从未真正改变过。在这种情况下,即使指针指向相同的位置也不需要重新加载数据,因为它们在指针的生命周期内不会改变。例如:
int max(int *restrict a, int *restrict b) {
return((*a > *b) ? *a : *b);
}
int main(void) {
int num = 3;
int max = max(&num, &num);
}
这是否是 restrict 的有效使用,即使它违背了它应该如何使用?像这样使用 restrict 关键字会导致未定义的行为吗?
最佳答案
正如埃里克在现已消失的评论中所说,来自 C99 draft standard
的关键短语6.7.3.1 restrict 的正式定义
是:
`If… X is also modified…`
6.7.3.1/10
中的示例支持此解释:
void h(int n, int * restrict p, int * restrict q, int * restrict r)
{
int i;
for (i = 0; i < n; i++)
p[i] = q[i] + r[i];
}
以及代码示例的以下注释:
illustrate how an unmodified object can be aliased through two restricted pointers. In particular, if a and b are disjoint arrays, a call of the form h(100, a, b, b) has defined behavior, because array b is not modified within function h.
因此您的具体示例似乎是定义的行为
,因为您没有修改a
或b
。
关于在某些情况下,您可以使用受限指针来访问同一对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18059205/