T
Trent Buck
(Note: C99 supports variadic macros, but C89 does not.)
I'm pretty sure what I'm trying to do is impossible, but I'll ask here
in case I'm missing something.
I'm trying to define generic, variadic arithmetic and boolean operators.
For example,
product (2, sum (3, 4), 5);
should expand to
(2) * ((3) + (4)) * (5);
Here is my pseudocode:
#define sum(x,y) \
(x) + (y)
#define sum(x, y, ...) \
(x) + sum (y, __VA_ARGS__)
int main (void)
{
sum (1, 2, 3, 4);
return 0;
}
Unfortunately, this has two problems:
- Macros cannot be overriden, hence the base case cannot be caught
generically. (You can define the base case as a function if the
definition (and declaration) precede the macro definition.)
- Macros expansion is not recursive (apparently).
For example, GCC's preprocessor outputs the following:
tmp.c:4:1: warning: "sum" redefined
tmp.c:1:1: warning: this is the location of the previous definition
# 1 "tmp.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "tmp.c"
int main (void)
{
(1) + sum (2, 3, 4);
return 0;
}
Can someone please either confirm that this is impossible in C, or
suggest how to go about it?
I'm pretty sure what I'm trying to do is impossible, but I'll ask here
in case I'm missing something.
I'm trying to define generic, variadic arithmetic and boolean operators.
For example,
product (2, sum (3, 4), 5);
should expand to
(2) * ((3) + (4)) * (5);
Here is my pseudocode:
#define sum(x,y) \
(x) + (y)
#define sum(x, y, ...) \
(x) + sum (y, __VA_ARGS__)
int main (void)
{
sum (1, 2, 3, 4);
return 0;
}
Unfortunately, this has two problems:
- Macros cannot be overriden, hence the base case cannot be caught
generically. (You can define the base case as a function if the
definition (and declaration) precede the macro definition.)
- Macros expansion is not recursive (apparently).
For example, GCC's preprocessor outputs the following:
tmp.c:4:1: warning: "sum" redefined
tmp.c:1:1: warning: this is the location of the previous definition
# 1 "tmp.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "tmp.c"
int main (void)
{
(1) + sum (2, 3, 4);
return 0;
}
Can someone please either confirm that this is impossible in C, or
suggest how to go about it?