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?

4
  • You mean I have better to rewrite it as a conventional routine and use va_list? Commented Feb 8, 2015 at 5: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);. Commented Feb 8, 2015 at 5: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. Commented Feb 8, 2015 at 5:28
  • @JonathanLeffler that link is stellar. Thanks. Commented Feb 8, 2015 at 5:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Jonathan Leffler and Rob. Terrific!! You have solved my problem in no time at all!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.