Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c++ - Is there a way to access the value of a local variable that has become hidden inside another scope?

I know if a variable is global, the you can always access its value by preceding the variable name with ::... but is there a way to access the value of a local variable that has become hidden inside another scope?

I thinking of something like this:

void f() {
    int x = 1;
    {
        int x = 2;
        //access the value of the variable x (with the 1 in it) inside here
    }
}

If the language doesn't support this, then I'm perfectly okay with some hacky solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could assign the outer x's address to a pointer object, then refer to it via the pointer in the inner scope (assuming you don't have another pointer object of the same name hiding it).

Or, as long as you're editing the code, you could change the name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...