How to call a variable defined inside main() but in outer scope

97 views Asked by At

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

2

There are 2 answers

3
Eutherpy On BEST ANSWER

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.

0
yosim On

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