Do functions have access to variables in the immediate outer scope without parameter input to the function in C++?

StackOverflow https://stackoverflow.com/questions/17448253

문제

Do functions have access to variables in the immediate outerscope without parameter input to the function in C++?

=========

Here is a code I am working on

#include...
void ReadGrid();
void SaveGrid();

int main(){
  ReadGrid();
}

void ReadGrid() {
  int m=1; 
  int n[]={1,2,3}; 
  vector<int> o(3,10);
  SaveGrid();
}

void SaveGrid() {
  int a=m;
  int b=n[1];
  int c=o[1];
}

Why can't I access the variables in the ReadGrid() functions in SaveGrid(), doesn't the local scope of SaveGrid() treat the scope of ReadGrid() as Global when SaveGrid() is called?

도움이 되었습니까?

해결책

Your question might be better formed thus:

When function a() calls function b(), does b() automatically get visibility into all of a()'s local variables?

And the answer is … no. They are still different block scopes, regardless of your call stack.

다른 팁

Each set of braces denotes a separate scope, so if you create a block with braces, and declare variables inside them, they will not be viisble outside of it. If you create nested blocks of braces, they have inner block has access to the outer block, but not the other way around.

This also applies not only to function (which always have their scope), but also to blocks inside a function as well.

i.e. Two different variables named i, no nameclash because of different scopes:

{
   int i;
}

{
   int i;
}

Here we have access.

{
   int i;
   {
      int x = i;   <== in scope
   }

   int y = x; <== error
}

If you want to have a set ov variables assoicated to some logical function, then you should put them inside a class or struct.

No, but this is where objects can come into play, e.g. in this pseudo code they share the same data:

class Grid {
private:
    int m;
    int n[];
    vector<int> o;

public:
    void ReadGrid(){
        // get m,n, and o
    }

    void SaveGrid() {
        // put m,n, and o
    }
}

int main(){
    Grid grid;
    grid.ReadGrid();
}

No what are trying to do is illogical.

If you want the value of m to be available to both ReadGrid and SaveGrid then you must defint "m" as a global variable and you can initialise it in ReadGrid and use the same value in SaveGrid.

Here is a snippet, for your reference

#include...
void ReadGrid();
void SaveGrid();

int m;// global variable 
int n[];//global variable

int main(){
ReadGrid();
}

void ReadGrid() {
m=1; 
n[]={1,2,3}; 
SaveGrid();
}

void SaveGrid() {
int a=m;
int b=n[1];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top