gpt4 book ai didi

c - 为什么下面代码中的 printf 语句打印的是一个值而不是垃圾值?

转载 作者:行者123 更新时间:2023-12-04 11:28:39 25 4
gpt4 key购买 nike

int main(){
int array[] = [10,20,30,40,50] ;
printf("%d\n",-2[array -2]);
return 0 ;
}

谁能解释 -2[array-2] 是如何工作的以及为什么在这里使用 [ ]?这是我作业中的一个问题,它给出了输出“-10”,但我不明白为什么?

最佳答案

从技术上讲,这会调用未定义的行为。引用 C11,章节 §6.5.6

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. [....]

所以,(array-2) 是未定义的行为。

但是,大多数编译器会读取索引,并且它可能会取消 +2-2 索引,[2[a] a[2] 相同,与 *(a+2) 相同,因此,2[a-2]*((2)+(a-2))],只考虑剩下的要求值的表达式,也就是*(a) 或者,a[0].

然后,检查 operator precedence

-2[array -2] 实际上与 -(array[0]) 相同。因此,结果是值 array[0],并且 -ved。

关于c - 为什么下面代码中的 printf 语句打印的是一个值而不是垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691675/

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