Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to variable of parent scope in c++?

Tags:

c++

scope

Let's imagine I have piece of code like this:

#include <iostream>

int main()
{

    int a = 5;
    {
        int a = 12;
        std::cout << a;
    }

    return 0;
}

I want to cout a==5 from outside scope, but main::a doesn't work surely. Is there any workaround?

like image 741
yanpas Avatar asked Jan 04 '16 17:01

yanpas


People also ask

Can a variable be accessed outside of its scope?

The var keyword is limited to function scope, meaning that new scope can only be created inside functions. Function and block scopes can be nested. In such a situation, with multiple nested scopes, a variable is accessible within its own scope or from inner scope. But outside of its scope, the variable is inaccessible.

What happens when a variable goes out of scope in C?

Nothing physical happens. A typical implementation will allocate enough space in the program stack to store all variables at the deepest level of block nesting in the current function. This space is typically allocated in the stack in one shot at the function startup and released back at the function exit.

What is scope script?

The Script scope is a useful place to store variables which must be shared without exposing the variable to the Global scope (and therefore to anyone with access to the session). For example, the following short script stores a version number in a script-level variable.

Why scope is used for variable?

One of the basic reasons for scoping is to keep variables distinct from each other in multiple parts of the program. For example the programmers can use same variables for all loops such i and j, this can lead collision of variables hence the scope of the variable is necessary to avoid collisions and for more security.


2 Answers

A (let's say) workaround:

int main()
{

    int a = 5;
    int *pa = &a;
    {
        int a = 12;
        std::cout << (*pa);
    }

    return 0;
}

Alternatively,

int main()
{

    int a = 5;
    int& ra = a;
    {
        int a = 12;
        std::cout << ra;
    }

    return 0;
}
like image 186
Ilya Avatar answered Oct 06 '22 02:10

Ilya


An alternative, it's similar to ilya answer but without polluting the parent scope

int main() {
  int a = 1;
  {
    int& outer_a = a;
    int a = 2;
    std::cout << outer_a;
  }
}
like image 29
Edwin Rodríguez Avatar answered Oct 06 '22 02:10

Edwin Rodríguez