[英]In the below program I was expected Infinite loop as a output. But output is 0, please help me with explain the concept behind it
void main()
{
int i;
int s=0;
while(i<30)
s+=i;
i++;
printf("Sum is %d",s);
}
/ output is 0,how? /输出为 0,怎么办? I was expecting infinite loop.
我期待无限循环。 /
/
i
is uninitialized. i
未初始化。 It can have any value.它可以有任何价值。 If it has a value greater/equal than 30, the loop will not execute and
s
remains 0.如果它的值大于/等于 30,则循环将不会执行并且
s
保持为 0。
void main()
{
int i;
int s=0;
while(i<30)
s+=i;
i++;
printf("Sum is %d",s);
}
i
is not being initialized properly, leading to undefined behaviour. i
未正确初始化,导致未定义的行为。 Change it to:将其更改为:
int main(void)
{
int i = 0;
int s=0;
while(i<30) // Infinite loop per OP's expectation
s+=i;
i++;
printf("Sum is %d",s);
return 0;
}
Note (Thanks @MikeCAT): To avoid implementation based messing, replace void main()
with int main(void)
.注意(感谢@MikeCAT):为了避免基于实现的混乱,请将
void main()
替换为int main(void)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.