variable declaration within the while loop C/C++

后端 未结 5 1652
失恋的感觉
失恋的感觉 2020-12-17 06:24

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

   main()
   {
   int i=3;       
   while(i--)
    {
      int i=100;
               


        
5条回答
  •  再見小時候
    2020-12-17 06:30

    Every scope in C++ (roughly speaking, each pair of braces that's not used for a special purpose such as array initialization) may contain its own local variable declarations. Writing int i = 100; within the loop specifies another variable named i that is different from the one outside the loop, and causes code within the scope that uses i, by default, to refer to the inner i instead of the outer one. However, the i-- in the loop condition still uses the outer i.

    When you replace int i = 100 with i = 100, now there is only one variable, which gets set to 100, decremented twice (once inside the loop and once by the loop itself), and re-set to 100, repeatedly.

提交回复
热议问题