0

I have this code:

#define PRINT(fmt, ...) printf("%s:%d: "fmt, __FILE__, __LINE__, ##  __VA_ARGS__)

It works well when I pass some value to it, eg PRINT("Hello, world"). But when I pass variable as an argument, eg. PRINT(somevar) it doesn't print the value of variable int somevar. How should I rewrite the macros to make it print variables as well?

cwenz1980
  • 3
  • 1
  • You mean I have better to rewrite it as a conventional routine and use va_list? – cwenz1980 Feb 08 '15 at 05:17
  • 1
    The macro will _not_ work unless the `fmt` (first) argument to the macro can be concatenated with the `"%s:%d: "` string, which means it too must be a literal. To print `int somevar`, the macro invocation must be `PRINT("%d\n", somevar);`. – Jonathan Leffler Feb 08 '15 at 05:20
  • In short, you can't invoke `printf` as `printf(some_int_var)` either; a format string is needed. This is no different (and in fact mandatory as a const-literal, as your logic now mandates it as concat-able, and a computed format string is not feasible, fair warning). The only immediate you can get away with sending to this is just like `printf`, a `char*` (const or otherwise) itself, and just like `printf` that would be discouraged for security reasons. – WhozCraig Feb 08 '15 at 05:28
  • @JonathanLeffler that link is *stellar*. Thanks. – WhozCraig Feb 08 '15 at 05:36

1 Answers1

3

The problem isn't in the macro. It is in how you use it. Essentially, your usage requires you to use PRINT with a format string, which must be a string literal that describes what to do with the subsequent arguments.

For example, try

PRINT("x = %d y = %d\n", x, y);

where x and y are variables of type int.

Rob
  • 1,966
  • 9
  • 13