gpt4 book ai didi

c - ANSI C 中的别名 : Is a = (double *) (&a) allowed

转载 作者:行者123 更新时间:2023-11-30 18:31:15 25 4
gpt4 key购买 nike

我想知道是否有任何东西阻止在 ANSI C 中执行此操作(或 C99 之前的任何具有严格别名规则的东西)。

const int n = 1000;
double *a = (double *) malloc(n * sizeof(double));

// Weird aliasing
a = (double *) (&a);

f(a, n);
free(a);

这个问题来自于英特尔编译器对以下代码进行向量化的事实

void f(double *a, int n) {
int k;
for (k = 0; k < n; ++k) {
a[k] = a[k] + 1.0;
}
}

没有 -ansi-aliasing 选项(默认情况下,英特尔编译器不使用严格的别名规则)。我的猜测是,它不应该,因为前面的代码改变了 a 在第一个循环中指向的内容。

弗朗索瓦

解释:由于经常有人询问其原因,您可以阅读 Chris Lattner 在 http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html 上的一篇文章。在“违反类型规则”部分。在我看来,他使用了严格的别名规则,因此 C99 声明他所做的事情是无效的。

最佳答案

没有。 a 的类型为 double*。因此 &a 的类型为 double**。您正在将 double** 转换为 double*。这在任何 C 版本中都是不允许的。

例如在 C89 中,请参阅 section 3.3 :

An object shall have its stored value accessed only by an lvalue that has one of the following types: [28]

  • the declared type of the object,

  • a qualified version of the declared type of the object,

  • a type that is the signed or unsigned type corresponding to the declared type of the object,

  • a type that is the signed or unsigned type corresponding to a qualified version of the declared type of the object,

  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or

  • a character type.

[Footnote 28] The intent of this list is to specify those circumstances in which an object may or may not be aliased.

关于c - ANSI C 中的别名 : Is a = (double *) (&a) allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25242990/

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