posted Mon 21-04-2008 16:49:08, in the c++ ( ) category
Recently I stumbled across the concept of variadic macros in C++. It's supported in modern versions of gcc for a long time, but MSVC++ supports it only from MSVC++ 2005.
And ofcourse, things wouldn't be normal if Microsoft dealt with them differently than gcc. Check out the following source code:
int sum( int factor, ... );
#define SUM(...) sum(1,__VA_ARGS__,-1)
#define SUM2(...) sum(2,__VA_ARGS__,-1)
Assume that you - for some reason - want a function that sums up a variable amount of integer values and multiply it with a certain factor. In that case the above function and defines could be of help to you. If you specify this:
int s = SUM(1,2,4,8)
it will be transformed into:
int s = sum(1,1,2,4,8,-1);
So far so good, nothing special, done that a million times. The -1 is there to indicate the 'end of the list'. Not a very good approach, but you need to know somehow when you've encountered the last actual parameter.
However, it becomes different when you DON'T specify any parameters, i.e.:
int s = SUM2();
In this case, you have a problem, as the above snippet will compile just fine in MSVC++2008, but gcc will bork. Gcc will expand that code to this:
int s = sum( 2, , -1 );
and claim it's invalid C++. And he'd be right. However, the Microsoft compiler assumes that because you didn't specify any parameters, you probably didn't want that comma to be there in the first place, and will transform the code into:
int s = sum( 2, -1 );
Well isn't that nice of the Microsoft compiler? It thinks FOR you! ^_^
-- Foddex
[ Back to blog listing ]
| More c++...20102009200820062005 |