1

In C++, before define a new variable, how we can find out is there a variable with this name or not?

5
  • 11
    Just define the variable and check for compilation errors. Commented Oct 22, 2013 at 14:25
  • Grep the source tree? Commented Oct 22, 2013 at 14:26
  • 2
    You 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. Commented Oct 22, 2013 at 14:26
  • 1
    Or you just write cout << VariableName; if it compiles, it exists, and you see its value Commented 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. Commented Oct 22, 2013 at 14:53

3 Answers 3

8

You can turn on compiler option for warning if a variable is shadowing another one. For instance for GCC this option is -Wshadow.

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

11 Comments

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.
@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.
You can - but then you wrote that action in the source code. And you can see there if you used a name before.
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); }
@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?
|
2

You should search all parent classes and that class with grep in text mode. And if you use a development studio program like Microsoft visual studio, you can type variable name and wait for auto-cast, it will show if the variable exists.

Comments

0

In general, C++ doesn't have reflection mechanisms, so you can't really check if a variable is defined using C++ code.

You have to use 3rd party tools for that.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.