gpt4 book ai didi

c - 这个指针别名是如何工作的?

转载 作者:行者123 更新时间:2023-12-01 13:19:12 24 4
gpt4 key购买 nike

https://kukuruku.co/post/i-do-not-know-c/

问题#7:

#include <stdio.h>
void f(int *i, long *l)
{
printf("1. v=%ld\n", *l); /* (1) */
*i = 11; /* (2) */
printf("2. v=%ld\n", *l); /* (3) */
}
int main()
{
long a = 10;
f((int *) &a, &a);
printf("3. v=%ld\n", a);
return 0;
}

小端系统上两个不同编译器的输出是:

1. v=10    2. v=11    3. v=11
1. v=10 2. v=10 3. v=11

第二个结果怎么可能?我不太明白如何通过引用严格别名来解释结果的解释。编译器是否完全忽略第 (2) 行?

最佳答案

引用 Wikipedia :

In C or C++, as mandated by the strict aliasing rule, pointer arguments in a function are assumed to not alias if they point to fundamentally different types, except for char* and void*, which may alias to any other type. Some compilers allow the strict aliasing rule to be turned off, so that any pointer argument may alias any other pointer arguments. In this case, the compiler must assume that any accesses through these pointers can alias. This can prevent some optimizations from being made.

这是违反规则的地方:

f((int *) &a, &a);
^ aliasing to different type (a is 'long')
^ passing the same variable with different type

问题是假设严格的别名规则,函数的第一个和第二个参数指向另一个位置,因为它们属于不同的类型。这就是作者解释的原因:

Therefore, we can assume that any long has not changed.

在这里:printf("2.v=%ld\n", *l);一个long值被取消引用。

这就是为什么这部分 (2) 在两个编译器上都是未定义的行为。

关于c - 这个指针别名是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314456/

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