RonErikson
RonErikson

Reputation: 97

Macro inside Macro

Consider the following code:

#define P1(x) x+x
#define P2(x) 2*P1(x)

int main()
{
    int a = P1(1) ? 1 : 0;
    int b = P2(a)&a;

    return 0;
}

Now, I thought that the compiler first replacing the macros with their values and so int b = 2*a+a&a; (and since a=1 then b=3). Why isn't it so?

Upvotes: 2

Views: 51

Answers (2)

Marco A.
Marco A.

Reputation: 43662

There's no precedence in your operation (it is just a textual substitution) thus, as you've noted,

#define P1(x) x+x
#define P2(x) 2*P1(x)

int a = P1(1) ? 1 : 0; // 1

and since & has lower precedence than +, it is equivalent to

int b = ((2 * a) + a) & a;

i.e. only the rightmost bit is set on b.

((2 * a) + a)  011 &
      a        001 =
--------------------
      b        001

Upvotes: 2

haccks
haccks

Reputation: 106112

This is because & has lower precedence than that of addition + operator. The grouping of operands will take place as

int b = ( (2*a + a) & a ); 

Therefore, (2*a + a) = 3 and 3 & 1 = 1 (011 & 001 = 001).

Upvotes: 2

Related Questions