Paul R
Paul R

Reputation: 213190

Confusing gcc error message in simple macro expansion

I've been looking at this too long and just can't see what the problem is:

#include <stdio.h>

typedef struct {
    int a;
    int b;
} S;

#define F(a,b) ( v.a = a, v.b = b, v )

int main(void) {
    S s, v;

    s = ( v.a = 1, v.b = 2, v ); // this works as expected

    printf("s = { %d %d } \n", s.a, s.b);

    s = F(1, 2); // but gcc complains about the macro equivalent

    printf("s = { %d %d } \n", s.a, s.b);

    return 0;
}

gcc complains:

In function 'main':
Line 17: error: expected identifier before numeric constant

The two assignments should be the same after pre-processing but evidently I'm missing something...

You can run the code here: http://codepad.org/0c1aUBLm

Upvotes: 0

Views: 628

Answers (2)

user529758
user529758

Reputation:

#define F(a,b) ( v.a = a, v.b = b, v )

When called with 1 and 2 as arguments, this expands to

( v.1 = 1, v.2 = 2, v)

Change the argument names of the macro to something different:

#define F(first,second) ( v.a = first, v.b = second, v )

Upvotes: 2

simonc
simonc

Reputation: 42205

Won't F(1, 2) expand to ( v.1 = 1, v.2 = 2, v ) ?

#define F(x,y) ( v.a = x, v.b = y, v )

should be better

Upvotes: 2

Related Questions