tags:

views:

383

answers:

5

Why does this not compile on VC 2005?

bool isTrue(bool, bool) { return true; }

void foo();

#define DO_IF(condition, ...) if (condition) foo(__VA_ARGS__);    

void run()
{
    DO_IF(isTrue(true, true)); // error C2143: syntax error : missing ')' before 'constant'
}

Running this through the preprocessor alone outputs:

bool isTrue(bool, bool) { return true; }

void foo();



void run()
{
    if (isTrue(true  true)) foo();; 
}

Notice the missing comma in the penultimate line.

Last Edit:

LOL!

bool isTrue(bool, bool) { return true; }

void foo();

#define DO_IF(condition, ...) if (condition) { foo(__VA_ARGS__); }

void run()
{
    DO_IF(isTrue(true ,, true)); // ROTFL - This Compiles :)
}
A: 

Your code compiles just fine in VS2008, if i change DO_IF to RETURN_IF. However, this should not change anything relevant for your error.

Edit: Still compiles without errors, even after your changes.

Timbo
A: 

I think that should work, except, shouldn't it be...

RETURN_IF(isTrue(b, !b));

and

RETURN_IF(isTrue(b,  b));
Suvesh Pratapa
It's a toy example, it doesn't matter what b is (look at the function)
Dolphin
Er...OK? He had DO_IF and I replaced it with RETURN_IF in my reply.Of course b doesn't matter! :)
Suvesh Pratapa
+1  A: 

Run your code through CPP (C preprocessor) to see what substitutions CPP does for your macro.

You could do it either by invoking cpp or providing -E parameter to compiler (if you use gcc, of course).

qrdl
+1 Most likely there is another macro that is messing up this macro.
Dolphin
+1  A: 

Various preprocessor implementations parse the commas greedily, treating them as separators for macro arguments. Thus, CPP thinks that you're asking "DO_IF" to do a substitution with two parameters, "isTrue(true" and "true)".

Mr Fooz
+3  A: 

Macros with indefinite numbers of arguments don't exist in the 1990 C standard or the current C++ standard. I think they were introduced in the 1999 C standard, and implementations were rather slow to adopt the changes from that standard. They will be in the forthcoming C++ standard (which I think is likely to come out next year).

I haven't bothered to track C99 compliance in Visual Studio, mostly because the only things I use C for anymore require extreme portability, and I can't get that with C99 yet. However, it's quite likely that VS 2005 lacked parts of C99 that VS2008 had.

Alternately, it could be that you were compiling the program as C++. Check your compiler properties.

David Thornley
Variadic macros are supported in VC2005.Though, it seems, with some implementation bugs.
Assaf Lavie