In C++, before define a new variable, how we can find out is there a variable with this name or not?
- 11Just define the variable and check for compilation errors.digital_revenant– digital_revenant2013-10-22 14:25:15 +00:00Commented Oct 22, 2013 at 14:25
- Grep the source tree?StoryTeller - Unslander Monica– StoryTeller - Unslander Monica2013-10-22 14:26:13 +00:00Commented Oct 22, 2013 at 14:26
- 2You know because C++ is not a dynamic language. It's possible to figure out exactly what variables are defined at any given time, including while you're writing code. If your scope is so wide that you're having trouble telling what is and isn't defined, you're doing something very wrong.user229044– user229044 ♦2013-10-22 14:26:16 +00:00Commented Oct 22, 2013 at 14:26
- 1Or you just write cout << VariableName; if it compiles, it exists, and you see its valueLegionair– Legionair2013-10-22 14:27:03 +00:00Commented Oct 22, 2013 at 14:27
- Note - if you define a variable in a one scope which already exists in a wider scope, the instance in the inner scope will hide the instance in the outer scope. If you try to redefine one in the same scope, you will get a compiler error due to ODR.John Dibling– John Dibling2013-10-22 14:53:02 +00:00Commented Oct 22, 2013 at 14:53
Add a comment |
3 Answers
You can turn on compiler option for warning if a variable is shadowing another one. For instance for GCC this option is -Wshadow.
11 Comments
Chavoosh
Well I in run-time mode I can not do this. I should be sure about presence of this variable, if it is not there I will define it.
Steve Jessop
@Chavoosh: C++ doesn't work like that. It is always possible to tell at compile time whether a particular name is in scope or not.
Henno
You can - but then you wrote that action in the source code. And you can see there if you used a name before.
Henno
As C++ is not interactive, YOU (the person) will not be able to define a new variable. In your code, try something like if(needArray){ std::vector<widget> v; v.push_back(Widget); }
Henno
@Chavoosh You are thinking in a completely un-C++-like way. What do you want to accomplish? When in your program, a condition determines that a new variable needs to be constructed, you write that. I do not get what your problem is with that - the condition? The name of the variable?
|