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?
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.
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[] .
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With