Using a character name as a string literal in a #define function macro
I want the debug function macro to work like this:
int myVar = 5;
PRINTVAR(myVar); // macro
// which expands to something like...
print("myVar: ");
println(myVar);
Basically, I want to use the identifier as a string literal as well as a variable.
I'm just a little tired of repeating myself when I want to dump a lot of variables to stdout.
My silly attempt, which of course doesn't work:
#define PRINT_VAR(x) Serial.print("x: "); Serial.println(x);
Is it possible?
+3
aaaidan
source
to share
3 answers
The "gating operator" is intended for this very case:
#define PRINT_VAR(x) (print(#x ": "), println(x))
+10
caf
source
to share
Look at the contraction operator , #, when you use a macro prefix with this, it puts it as a string, not expands it.
+2
gbjbaanb
source
to share
Providing sample code, I don't know if you are talking about C or Java. However, here's what I'll do in C:
#define DEBUG(X, ...) fprintf(x, __VA_ARGS__);
And use it:
DEBUG (srderr, "my mistake \ n");
0
Halim qarroum
source
to share