문제

Here is my code, im trying to call the variable defined inside the main(), but outside the current scope:

#include<iostream>
int main()
{
    int asd = 10;  //***
    while (True) 
    { 
        int asd = 100;
        asd -= 1;   //***is it possible to use the 'asd' defined before while loop
        if (asd ==0) break;
    }
}

best regards Eason

도움이 되었습니까?

해결책

No. The int asd = 100; is masking the old asd variable.

What you want (I suppose) is to just assign the value 100 to asd, which (and I'm sure you know this) you could simply do by writing asd = 100;. There is, of course, one more issue: you would want to do that before the while loop - otherwise, you're going to have an infinite loop because at the beginning of every iteration the value of asd will be 100.

You're missing a ; after asd = 100, by the way.

다른 팁

If you REALY want to access the "outside" asd, before redefining it, create a reference to it:

int main()
{
   int i = 10;
   {
      int &ri = i;
      int i = 12;
      std::cout <<"i="<<i<<" ri = "<<ri<<std::endl;
      ++i;
      ++ri;
      std::cout <<"i="<<i<<" ri = "<<ri<<std::endl;
   }
   std::cout <<"i = " <<i <<std::endl;
}

will output:

i=12 ri = 10
i=13 ri = 11
i = 11
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top