In C++, I have a situation where I want to access a variable defined in the local scope of the main function from an inner block scope. Here’s a simplified version of my code:
#include <iostream>
using namespace std;
int var = 10; // Global variable
int main(int argc, char *argv[])
{
int var = 20; // Local variable in main
{
int var = 40; // Local variable in inner block
cout << ::var; // Prints 10 (the global variable)
// But I want to print the `var` in the `main` scope (20)
}
return 0;
}
I want cout to print 20, which is the value of var in the scope of main. However, using ::var only gives me the global variable value 10.
Is there a way in C++ to access the local variable in main (value 20) from within this inner block, bypassing the local variable defined in the inner block (value 40)?
I know that C++ doesn’t have an equivalent of Python’s nonlocal keyword, but is there a workaround or technique that allows accessing a variable from an enclosing scope without changing the variable names?
There is no way to accomplish that. The language does not provide a way to differentiate between the first var
in main
from the second var
.
If you ever write production code, please refrain from using such variables. It will lead to buggy code. You will be confused about which variable is in scope in a given line of code.