Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a C macro for appending /n to every printf

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
like image 862
Doug Null Avatar asked Feb 08 '23 15:02

Doug Null


1 Answers

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);
like image 105
M Oehm Avatar answered Feb 11 '23 05:02

M Oehm