while 循环中的变量声明 C/C++ [英] variable declaration within the while loop C/C++

查看:81
本文介绍了while 循环中的变量声明 C/C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的说法,while 循环应该是无限的,但它只运行三次

according to me following while loop should be infinite but it runs only thrice

   main()
   {
   int i=3;       
   while(i--)
    {
      int i=100;
      i--;
      printf("%d..",i);
    }
   }

它输出99..99..99

但据我说它应该无限次运行,因为每次控制进入 while 循环时,它的值都是 100.所以它永远不会达到零.只是为了试验,我在 while 循环中用 i=100; 替换了 int i=100; ,现在它无限次运行..WHY???

but according to me it should run infinite times as every time control enters while loop it gets value 100.so it will never reach zero. just to experiment i replaced int i=100; with i=100; in side the while loop and now it runs infinite times..WHY???

推荐答案

检查条件的变量 i 是你在 main() 中声明的不是那个循环内.

The variable i that checks the condition is the one you declared in main() not the one inside the loop.

两者是不同的变量,您将它们混淆为一个,编译器不会像您一样容易混淆.

Both are different variables you are confusing them as one, the compiler doesn't get confused as easily as you were.

在循环内 i 指的是你在 { } 内但在 { 外声明的那个code>} i 指的是在 main()

Inside the loop i refers to the one you declared inside the { } but outside the { } the i refers to the one declared in main()

这篇关于while 循环中的变量声明 C/C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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