-5
#define A 1+2
#define B 4+3

int main()
{
   int val = A*B;
   printf("%d",val);
}

Here A and B is defined, and val is (A*B). What is the correct output?

BlindCat
  • 295
  • 1
  • 2
  • 8
  • 1
    http://stackoverflow.com/questions/3742822/preprocessor-output – 001 Sep 21 '15 at 12:52
  • 2
    It is trivial to find out by performing the substitution yourself: `A*B` --> `1+2*4+3`, and applying primary school math skills. – molbdnilo Sep 21 '15 at 12:55
  • 1
    How do you determine the correctness of the output? (1) It is what you think it should do, or (2) it is what the compiler tells you it is? Do they differ? – Jongware Sep 21 '15 at 12:57
  • 2
    `12` (you forgot to state what you **think** is correct). Just tell me where to pick up the car I won. – too honest for this site Sep 21 '15 at 13:04

2 Answers2

3

Let's trace the expansion and calculation manually.

A*B -> 1+2*4+3 -> 1+8+3 -> 12

As a result, the output will be 12

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
2

This is a common issue with Macros. When you define something even as x+y in a macro it is advisable to first rap them in () so as to "protect" the operation. As such it would be better to define A as (1+2) etc. Otherwise you get the output 1+2*4+3=12 as people have stated above.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
arduic
  • 659
  • 3
  • 12