108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
|
/* There is a little bit of trickery required to handle the difference
* between 1 and 0 arguments, since a blank space followed by a comma counts
* as two arguments to the CPP.
*/
#define NUM_ARGS1(_20,_19,_18,_17,_16,_15,_14,_13,_12,_11,_10,_9,_8,_7,_6,_5,_4,_3,_2,_1, n, ...) n
#define NUM_ARGS0(...) NUM_ARGS1(__VA_ARGS__,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0)
#define NUM_ARGS(...) IF(DEC(NUM_ARGS0(__VA_ARGS__)))(NUM_ARGS0(__VA_ARGS__),IF(IS_PAREN(__VA_ARGS__ ()))(0,1))
#include <stdio.h>
#include <math.h>
/* Can you say: DEFAULT ARGUMENTS IN C90? */
void greet1( const char* name ) { printf( "Hello, %s!\n", name ); }
#define greet0() greet1( "world" )
#define greet(...) CAT( greet, NUM_ARGS( __VA_ARGS__ ) )( __VA_ARGS__ )
/* There are other uses as well... */
double arctan2( double a, double b ) { return atan2( a, b ); }
double arctan1( double a ) { return atan( a ); }
#define atan(...) CAT( arctan, NUM_ARGS(__VA_ARGS__) )( __VA_ARGS__ )
int sum3( int a, int b, int c ) { return a + b + c; }
int sum2( int a, int b ) { return a + b; }
int sum1( int a ) { return a; }
int sum0() { return 0; }
#define sum(...) CAT( sum, NUM_ARGS( __VA_ARGS__ ) )( __VA_ARGS__ )
int main()
{
greet();
greet( "Sally" );
printf( "%f\n", atan( .5 ) );
printf( "%f\n", atan( 3, 4 ) );
printf( "%d\n", sum( 2, 7 ) );
printf( "%d\n", sum() );
return 0;
}
|