MY_PRINT
is a macro throughout the code, which just does printf.
I want to temporarily modify it to also append \n after every printf.
However, when I do this:
#define SENS_PRINT(x) printf(x); printf("\n")
MY_PRINT( "\n #%d: %c ", ++command_line_number, sensor_operation_code );
...the output is trash: #3405240: <alpha symbol>
This prints ok, but no \n at end:
#define SENS_PRINT printf
You want your macro to be able to take various arguments, just like the real printf. You can do this with variadic macros.
There's also a danger that two separate expressions aren't interpreted as the macro suggests when the macro is the only expression in a conditional code block. Think about what the macro does if you say if (flag) SENS_PRINT(...);
. One way to prevent this is to wrap the macro in a do { ... } while(0)
block.
A variadic macro that appends a newline to printf
could look like this:
#define PRINTFLN(...) do { printf(__VA_ARGS__); puts(""); } while (0)
You can use it just like printf
:
PRINTFLN("Hello %s!", "cruel world");
if (flag) PRINTFLN("%d + %d == %d", x, y, sum);
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