0

Does someone know if in C++ is there a function to get the name of all the variables defined in a code?

Example code:

int main() { double Var1; double Var2; UnknownFunction(); } 

In this case the function I'm searching for(UnknownFunction) should output a vector of strings containing "Var1" and "Var2".

Thank you in advance.

11
  • 1
    Why do you want to do this? And will all of the variables you're interested in be of the same type (double here)? Commented Dec 24, 2019 at 16:06
  • 1
    What are you really trying to do? Why do you think you need this? Commented Dec 24, 2019 at 16:07
  • 1
    There is no way to do that. If you tell us more about what you're trying to do, we might be able to suggest a different solution. Commented Dec 24, 2019 at 16:07
  • 1
    What you're looking for is called reflection, and C++ doesn't support this. Some scripting languages like Python and Javascript do. Instead, you make your own symbol table, and have a map of strings to values. Your formula solver can use the symbol names to get and set values in the table. Commented Dec 24, 2019 at 16:13
  • 1
    @FGP92 You have asked an X-Y question. The thing you really want to do is in your last comment - you'd do better to ask that question. Do you really mean "equation solver" or more simply an "expression evaluator"? I say more simply - it is still not that simple. What you need is a string to value look-up or hash table, the variables declared in your C code are irrelevant to the variables used in your expression evaluator. Commented Dec 24, 2019 at 16:17

1 Answer 1

5

When C++ code has been compiled to machine code, the symbol names are resolved to explicit memory addresses by the compile/link process and are not available to the program at run time, so the question makes no real sense.

Symbolic information is retained for use in a debugger and a debugger can present all variables in scope.

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

8 Comments

The question is about C++. Also there's no such thing as "a compiled language".
@LightnessRacesBY-SA3.0 Corrected C++. Not sure what your point about "compiled language" is - perhaps a little pedantic? The term serves my purpose for this discussion - in the sense that the compiler generates machine code where variable names are not retained.
@LightnessRacesBY-SA3.0 Show me a C interpreter that's not an online "compiler"
@LightnessRacesBY-SA3.0 : Nonetheless your objection has led me to modify the text for a perhaps clearer and as a side-effect hopefully less objectionable text.
Thank you very much for the answers. I already thought to create a vector of objects "variabile" each containing name and value and then creating a map that links the name to the corresponding value. Thank you for your suggestions.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.