Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting arguments in C++ preprocessor

Some legacy code I am working on has a macro which returns a comma-separated list intended to be used as function arguments. This is ugly, but the configuration file contains many of these and it would be difficult to change now.

#define XY1 0,0
#define XY2 1,7
...

void fun_point(x,y);

fun_point(XY1);

This works fine as long as it is a function being called. However, when trying to call another macro with the parameters, the whole string is considered as one argument rather than split at the comma into two arguments

#define MAC_POINT(x,y) (x+y)
MAC_POINT(XY1) #not expanded by preprocessor 

Is there a workaround for this problem without changing the XY definitions?

like image 974
Quantum7 Avatar asked Dec 12 '12 16:12

Quantum7


1 Answers

Kinda. The following works:

#define MAC_POINT(x,y) (x+y)
#define MAC_POINT1(xy) MAC_POINT(xy)
#define XY x,y
MAC_POINT(x,y)
MAC_POINT1(XY)

However, you have to change from MAC_POINT to MAC_POINT1 if you only have one argument.

Another possibility is this:

#define MAC_POINT(x,y) (x+y)
#define MAC_POINT1(xy) MAC_POINT xy
#define XY x,y
MAC_POINT1((x,y))
MAC_POINT1((XY))

Now you have to change all your calls to the macro, but at least they're consistent.

like image 102
rici Avatar answered Jan 13 '23 20:01

rici