简体   繁体   中英

C macro with {}

I have defined the following struct in C:

typedef struct point{
    float x;
    float y;
    float z;
} Point;
typedef Point Vector;

and the following macro:

#define sub(p1,p2)      {p1.x-p2.x,p1.y-p2.y,p1.z-p2.z}

That is used like this:

void fun(Point p0, Point p1){
    Vector u;
    u=sub(p1,p0);
}

From what I've read this should work, or maybe I'm missing something maybe even obvious... but I'm getting the following error that I don't understand what I'm supposed to look do:

error: expected expression before '{' token

So basically I just want to obtain the same as:

struct point u={p1.x-p0.x,p1.y-p0.y,p1.z-p0.z}

I really have no idea of what am I doing wrong... Thank you.

[EDIT] included some more function details so you can see where I think my mistake was. Not initializing with the variable declaration because after changing

Vector u;
u=sub(p1,p0);

to

Vector u=sub(p1,p0);

It works but I still don't understand why.

This has nothing to do with the macro: the problem would persist even if you expand this macro by hand. The reason why this is failing is that initializer list in an assignment must be composed of constant expressions , so p1.x is not allowed.

If you are using C99, change your macro to use a compound literal , like this:

#define sub(p1,p2)      (Vector){p1.x-p2.x,p1.y-p2.y,p1.z-p2.z}

This will let you use the macro in assignments as well as in initializers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM