Reputation: 7346
I want a debug function-macro that works 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 getting a bit sick of repeating myself when I want to dump out a whole lot of variables to the stdout.
My silly attempt, which of course doesn't work:
#define PRINT_VAR(x) Serial.print("x: "); Serial.println(x);
Is this possible?
Upvotes: 3
Views: 6664
Reputation: 52689
Look up the stringifying operator, #, when you use the macro id prefixed with this, it puts it as a string instead of expanding it.
Upvotes: 2
Reputation: 14103
Giving your code example, I don't know if you're talking about C or Java. However, here is I'll do in C :
#define DEBUG(X, ...) fprintf(x, __VA_ARGS__);
And to use it :
DEBUG(srderr, "my error\n");
Upvotes: 0
Reputation: 239331
The "stringizing operator" is designed for precisely this case:
#define PRINT_VAR(x) (print(#x ": "), println(x))
Upvotes: 10