3

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?

2
  • 2
    You should be very cautious about embedding semicolons in macros. You certainly couldn't use what you wrote just anywhere. And normally, there'd be a semicolon after the macro invocation, so the expansion would have two semicolons in a row. It's not directly a syntax error because the second semicolons marks the end of an empty statement. Consider using the do { Serial.print("x: "); Serial.println(x); } while (0) idiom if you must use semicolons. Note that at least one answer carefully avoids semicolons by using a comma operator instead. Commented Mar 25, 2012 at 4:21
  • @JonathanLeffler Cheers for the tip! I noticed the commas, makes sense. Commented Mar 25, 2012 at 4:35

3 Answers 3

10

The "stringizing operator" is designed for precisely this case:

#define PRINT_VAR(x) (print(#x ": "), println(x))
Sign up to request clarification or add additional context in comments.

2 Comments

wow, wth. Why does a comma work there? Who gets it? The preprocessor or the compiler?
@enigmaticPhysicist: One of the operators in C is the comma operator, which has the form <expression> , <expression>. It evaluates the left hand expression, then has a sequence point (where all side-effects settle), then evaluates the right hand expression. The result and type of the operator is the same as that of the right hand expression. Note that the commas in the argument list to a function call are not comma operators, they are just punctuation.
2

Look up the stringifying operator, #, when you use the macro id prefixed with this, it puts it as a string instead of expanding it.

2 Comments

Brilliant. Thanks for including a reference.
shame the phone editor wouldn't let me embed the link or I'd have done a better job. Time to fix that.
0

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");

1 Comment

I should have made it clear in the question that I wanted to avoid typing the variable name twice when debugging it to output. And yes, C is correct! cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.