3
void foobar(){
    int local;
    static int value;
     class access{
           void foo(){
                local = 5; /* <-- Error here */
                value = 10;
           }
     }bar;    
}   
void main(){
  foobar();
}

Why doesn't access to local inside foo() compile? OTOH I can easily access and modify the static variable value.

1
  • 4
    The return type of main() must always be int. Commented Oct 14, 2010 at 5:06

4 Answers 4

1

Inside a local class you cannot use/access auto variables from the enclosing scope. You can use only static variables, extern variables, types, enums and functions from the enclosing scope.

Sign up to request clarification or add additional context in comments.

Comments

1

From standard docs Sec 9.8.1,

A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. Declarations in a local class can use only type names, static variables, extern variables and functions, and enumerators from the enclosing scope.

An example from the standard docs itself,

int x;
void f()
{
static int s ;
int x;
extern int g();
struct local {
int g() { return x; } // error: x is auto
int h() { return s; } // OK
int k() { return ::x; } // OK
int l() { return g(); } // OK
};
// ...
}

Hence accessing an auto variable inside a local class is not possible. Either make your local value as static or a global one, whichever looks appropriate for your design.

Comments

0

Make local static and then you should be able to access it

Comments

0

Probably because you can declare object that lives out of scope of the function.

foobar() called // local variable created;
Access* a = new Access(); // save to external variable through interface
foobar() finished // local variable destroyed

...


savedA->foo(); // what local variable should it modify?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.