Gautam Krishna Gautam Krishna - 2 months ago 24
C++ Question

__LINE__ macro not working when define printf's macro

The LINE macro gives random number and FILE macro gives a null when, the "printf" is defined with another macro. In the following code, I have shown the macro used for "printf" and the function (which is a method of a class), where the macro is used:

#define OTConsolePrint(x) printf(x)


...

void parseArray(float* arr)
{
if (arr == NULL)
{
printf("Line: %d\n", __LINE__);
OTConsolePrint("Null pointer at \nLine: %d\nFile: %s\n", __LINE__, __FILE__);
}
}


gives me:

Line: 39
Null pointer at
Line: 1964696
File: (null)

Answer

Your "macro-function" takes just one argument:

#define OTConsolePrint(x) printf(x)

You call it, instead, with more than one argument:

OTConsolePrint("Null pointer at \nLine: %d\nFile: %s\n", __LINE__, __FILE__);

Actually I don't even think it compiles.


Anyway in order to have variadic argument you can do:

#define OTConsolePrint(STR, ...) printf(STR, __VA_ARGS__)

It works as expected.