Questions
I want to access a local variable of main function in another scope.
My goal is to print 20 in cout.
How can I do this?
How is it possible in C++?
int var = 10;
int main(int argc, char *argv[])
{
int var = 20; // this var
{
int var = 40;
cout << ::var; // I want to print `var` variable in main scope.
// But this command print global variable.
}
return 0;
}
Answers
You can t access a variable (in some cases extern can be used but not in your code) outside its scope. So, you can t use variable var (declared inside the innermost block) outside its scope. For example,
int var = 10;
int main(int argc, char *argv[])
{
int var = 20; // this var
{
int var = 40;
}
cout << var; // this will access var declared first and prints 20
return 0;
}
And trust me, there is no need to declare and use variables in this way. It will lead to buggy code. Remember, if you use GCC or clang, always use -Wshadow compiler flag while compiling as it shows warning if something like this is done anywhere in the code. Try to include it in your IDE or makefile if you don t compile your code from terminal.
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/38289456/how-can-i-use-local-variable-in-another-scope-in-c
Related