变量未在for循环条件中声明C - 仍然工作 [英] variable not declared in for loop condition in C-still works

查看:163
本文介绍了变量未在for循环条件中声明C - 仍然工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的代码来找到 C 中所有数字的总和,当我编译并运行它时,它是成功的。
但是,后来才知道,我在for循环的条件中为变量 n 输入了
我很困惑这个程序是如何工作的,即使没有赋值给条件变量。
我想澄清一下。

  #include< stdio.h> 
void main()
{
int no,a,b,n,sum = 0;
printf(输入要添加的数字);
scanf(%d,& no);
for(int i = 0; i< n; i ++)
{
a = no%10;
b = no / 10;
sum = a + sum;
no = b;
}
printf(总和是%d,总和);



$ b $ div class =h2_lin>解决方案


我很困惑这个程序如何工作


那么,works这里是一个很差的观察/决定。这是未定义的行为



您试图在 时使用自动局部变量 n 的值。这引用了UB。



引用 C11 标准,第6.7.9节


如果具有自动存储持续时间的对象未被显式初始化,则其值为
不确定。 [b]

所以,在你的情况下, n 符合上述标准,因此内容是不确定的。

现在,在这之后,如果您尝试使用一个变量,而它保持不确定的值,或者


  • 没有收到地址

  • 可以有陷阱表示形式



使用会导致未定义的行为。这就是这种情况。

也就是说,对于托管环境, main()至少是 int main(void)


I wrote the below code to find the sum of all digits in C, and when I compiled and ran it, it was successful. But, only later I realized that i had not entered any value for the variable 'n' in the for loop's condition. I'm confused on how this program works, even when there is no value assigned to the condition variable. I would like to be clarified of the same.

#include<stdio.h>
void main()
{
int no,a,b,n,sum=0;
printf("Enter the number to be added");
scanf("%d",&no);
for(int i=0;i<n;i++)
    {
     a=no%10;
     b=no/10;
    sum=a+sum;
    no=b;
    }   
printf("The sum is %d",sum);
}

解决方案

I'm confused on how this program works

Well, "works" is a very poor observation / decision here. This is undefined behavior.

You're attempting to use the value of an automatic local variable n while it is indeterminate. This invokes the UB.

To quote the C11 standard, chapter §6.7.9

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]

So, in your case, n meets the criteria described above, and hence the content is indeterminate.

Now, after that, in case you try to use a variable while it holds indeterminate value and either

  • does not have the address taken
  • can have trap representation

the usage will lead to undefined behavior. That is exactly the case here.

That said, for a hosted environment, the conforming signature of main() is int main(void), at least.

这篇关于变量未在for循环条件中声明C - 仍然工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆