【发布时间】:2017-11-22 17:37:09
【问题描述】:
我在cppreference看到了下面的例子。
void f(int n, int * restrict p, int * restrict q)
{
while(n-- > 0)
*p++ = *q++; // none of the objects modified through *p is the same
// as any of the objects read through *q
// compiler free to optimize, vectorize, page map, etc.
}
void g(void)
{
extern int d[100];
f(50, d + 50, d); // OK
f(50, d + 1, d); // Undefined behavior: d[1] is accessed through both p and q in f
}
在那个例子中,调用f(50, d + 50, d); 是可以的。
但是,我不明白,打电话给f(50, d + 1, d);是未定义的行为。为什么?
【问题讨论】:
-
因为函数
f中的对象d[1]是通过p和q访问的。评论是这么说的。 -
我不认为 restrict 在这里有帮助,因为“指针的生命周期”是函数调用 - 无论如何都会影响两个指针。正常的未定义行为适用
-
@MartinBeckett in function
f两个指针都受到限制,但在不同时间指向同一个对象。 -
@EugeneSh。 d 保存数组 d[0] 的基地址
-
@rsp 嗯什么?
d是一个数组。d[0]是一个数组元素。
标签: c undefined-behavior restrict