Why the output is different when we add 'int' tag twice in a program when using 'for' loop?

前端 未结 4 814
滥情空心
滥情空心 2021-01-15 12:26

I am a learner and new to C language. While I was creating a function which will give power of two numbers using for loop I encounter that using int declaration before loop

4条回答
  •  礼貌的吻别
    2021-01-15 12:48

    Because the 'scope' of r in the second code is inside the loop, when you leave the loop the variable is not longer valid.

      for (k = 1; k <= y; k++)
      {
           int r = r * x; //here you create the variable
      } //here it is destroyed
    

    In c/c++ the variables are local to a scope, when you leave the scope you loose the variable. Everything inside {} is a scope (internal to the outside scope). Inside scopes can see variables of outside scope.

    void func()
    { // begin scope of a function
    
       // can't see any variables defined inside the scope of the while
       // they don't exists yet
       while ()
       { // begin scope of a while
         // can see variables defined inside the scope of the function
       }
    
       // can't see any variables defined inside the scope of the while
       // they don't exists anymore
    }
    

提交回复
热议问题