How to print the variable name in C?

Asked

Viewed 838 times

6

Example:

I have an entire variable called menino, how do I print on a printf() the name of that variable, i.e. "menino"

1 answer

7


I can do with a trick in the preprocessor. I found this macro in response in the OS:

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

The secret is in the # which transforms the text of the code (part of which is the written code) into literal text (a string) which can be used by the code. Obviously you do not need to use the strderr or even the fprintf.

int i = 0;
DUMP(i); //será convertido para fprintf(stderr, "%s = %x", "i", i);

I put in the Github for future reference.

I see little use for this in normal codes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.