I’ve been banging my head trying to write a proper #define function-like macro but am getting stuck. Here’s the example I’m working with:
#include <iostream>
#define pMAKE(x,y,z,dest)\
(dest).(x) = (x);\
(dest).(y) = (y);\
(dest).(z) = (z);
struct pt {
double x, y, z;
};
int main() {
pt p;
pMAKE(0,1,2,p);
return 0;
}
And the errors I’m getting:
A.cpp: In function ‘int main()’:
A.cpp:13: error: expected unqualified-id before ‘(’ token
A.cpp:13: error: expected unqualified-id before ‘(’ token
A.cpp:13: error: expected unqualified-id before ‘(’ token
What do the errors mean and why am I getting them? I managed to get the following to work the way I wanted, but I honestly just got lucky and I seriously don’t understand what’s going on.
#define pMAKE(X,Y,Z,dest)\
dest.x = (X);\
dest.y = (Y);\
dest.z = (Z);
I appreciate every bit of help!
With the first version of your macro,
pMAKE(0,1,2,p);expands toIn other words, you’ve pre-processed away references to the
x,y,zmembers ofptby usingx,y,zas both variable names (on the left of the assignments) and labels to be replaced by the pre-processor (on the right of the assignments).(As noted by Konrad Rudolph) Your macro still has another serious error unfortunately. Consider code of the form
which expands to
You can fix this (and get rid of that annoying extra semi-colon) by changing your macro to