#include<stdio.h>
void main(void)
{
int a[5]={90,78,77,98,98}, b[5]={80,45,67,88,57}, c[5]={88,99,65,55,74},total[3],i,j;
for(j=0;j<=4;j++)
{
total[0]+=a[j];
total[1]+=b[j];
total[2]+=c[j];
}
for(i=1;i<=3;i++)
{
printf("%d행의 가로 합 : %d\n",i,total[i-1]);
}
}
total[0]
和 total[1]
是正确的值,但 total[2]
是错误的值。我找不到自己的错。能解释一下吗?
最佳答案
这里的第一个问题是在代码中
total[0]+=a[j];
total[1]+=b[j];
total[2]+=c[j];
您在哪里使用 total[n]
s 未初始化。它们包含不确定的值,使用它们会调用 undefined behavior .
详细说明一下,total
作为未初始化的自动局部变量,数组元素的初始值是不确定的。通过使用+=
运算符对这些元素进行操作,您尝试读取(使用)不确定的值,因此它会在您的情况下调用 UB。
相关引用来自C11
,第 §6.5.16.2 章,复合赋值,
A compound assignment of the form
E1 op= E2
is equivalent to the simple assignment expressionE1 = E1 op (E2)
, except that the lvalueE1
is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. IfE1
has an atomic type, compound assignment is aread-modify-write
operation withmemory_order_seq_cst
memory order semantics.
因此,通过使用+=
对于未初始化的值,_您正在尝试读取(或使用)具有不确定值的变量,这会导致 UB。
如果需要,您可以使用类似
的语法来初始化整个数组 int total[3] = {0};
它将数组的所有元素初始化为0,这基本上就是您所期望的。
也就是说,void main(void)
不是 main()
的一致签名在托管环境中,根据规范,它应该是 int main(void)
,至少。
关于c - 数组元素(使用复合赋值运算符后)会产生垃圾值,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39491498/