0
#include <iostream>

using namespace std;

#define debug(x) cout<<#x<<": "<<(x)<<endl;

int main() {

    int a = 0;
    debug(a)
    return 0;
}


the output is: a:0
I want to print the name of variable like a
can I do it by a function not use define

Leon
  • 41
  • 7
  • No. Functions have no information about how their arguments were constructed. – Botje Aug 31 '21 at 12:27
  • 1
    "Stringification" with `#` is a preprocessor macro-only thing. You can create a macro to *call* a function, passing e.g. `#x` as argument, but you can't use the operator in plain C++ code. – Some programmer dude Aug 31 '21 at 12:28
  • 1
    You will regrettably need a macro. The name of a variable is lost at runtime so something must be done at compile time. – Pepijn Kramer Aug 31 '21 at 12:30
  • Are you willing to build with debug information? And then use that debug information to reflect upon the string of the name associated with a variable? It will be extraordinarily slow, but it will work, and won't be portable. – Eljay Aug 31 '21 at 12:46

1 Answers1

0

i think the answers here can help you : generic way to print out variable name in c++ and it seems the only way is using macro!

Ali
  • 376
  • 5
  • 16
  • 2
    Please take some time to read or refresh [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) Link-only answers like your are generally discouraged. And with a link to Stack Overflow itself it's better to vote to close as a duplicate instead. – Some programmer dude Aug 31 '21 at 12:44