Programmatic way to get variable name in C?

前端 未结 10 1803
广开言路
广开言路 2020-11-29 23:08

I am developing a tool to dump data from variables. I need to dump the variable name, and also the values.

My solution: Store variable name as a string, and print th

10条回答
  •  既然无缘
    2020-11-29 23:38

    Try this.

    #define MACRO_VARIABLE_TO_STRING(Variable) ((void) Variable,#Variable)
    

    Code (void) Variable is void conversion which is no-op then there is the comma operator and macro stringify. So the net result is const char* containing variable name with compiler check is variable really exists.

    Now you have the name of your variable and you can use printf() to print its value.

提交回复
热议问题