2

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?

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.