Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic way to get variable name in C?

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 the "variable name", followed by its value.

Is there any programmatic way to know the variable name?

like image 301
Alphaneo Avatar asked Oct 26 '09 04:10

Alphaneo


People also ask

Can you print the name of a variable in C?

How to print and store a variable name in string variable? In C, there's a # directive, also called 'Stringizing Operator', which does this magic. Basically # directive converts its argument in a string. We can also store variable name in a string using sprintf() in C.

How do you print variable names?

Print Variable Name With a Dictionary in Python We stored the variable values as keys and the corresponding variable names as the vnames dictionary values. Whenever we have to print the name of a particular variable, we have to pass the value inside vnames[] .

How do you print a variable in C?

This number is stored in the number variable. printf("Enter an integer: "); scanf("%d", &number); Finally, the value stored in number is displayed on the screen using printf() . printf("You entered: %d", number);

What is #variable in C?

Variables are containers for storing data values. In C, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123. float - stores floating point numbers, with decimals, such as 19.99 or -19.99.


2 Answers

You could try something like this:

#define DUMP(varname) fprintf(stderr, "%s = %x", #varname, varname); 

I used to use this header I wrote, when I was new to C, it might contain some useful ideas. For example this would allow you to print a C value and provide the format specifier in one (as well as some additional information):

#define TRACE(fmt, var) \         (error_at_line(0, 0, __FILE__, __LINE__, "%s : " fmt, #var, var)) 

If you're using C++, you could use the type of the passed value and output it appropriately. I can provide a much more lucrative example for how to "pretty print" variable values if this is the case.

like image 131
Matt Joiner Avatar answered Sep 21 '22 07:09

Matt Joiner


In C, variable names exist during the compile step (and the link step, if the variable is global), but are not available at runtime. You must choose a solution that involves a literal string indicating the variable name.

like image 20
Greg Hewgill Avatar answered Sep 23 '22 07:09

Greg Hewgill