简体   繁体   English

在下面的程序中,我期望无限循环作为输出。 但是输出是0,请帮我解释一下它背后的概念

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM