Search code examples
c++coperators

Why is the result of this 62?


The only thing that passed to my mind was, MULT((3+2)(5*4))= 100, not 62? What is the explanation?

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define ADD(x1, y1) x1 + y1
#define MULT(x1,y1) x1 * y1


int _tmain(int argc, _TCHAR* argv[])
{
    int a, b, c, d, e, f, g;
    a = 2;
    b = 3;
    c = 4;
    d = 5;
    e = MULT(ADD(a,b),MULT(c,d));
    printf("the value of e is: %d\n", e);
    system("PAUSE");
}

Solution

  • When the macros are expanded, this:

    MULT(ADD(a,b),MULT(c,d))
    

    becomes:

    a + b * c * d
    

    which, replacing the variables with their values, is equivalent to:

    2 + 3 * 4 * 5
    

    and the value of this expression, evaluated according to the precedence rules, is 62, because multiplication has higher precedence than addition.

    Don't use macros for this purpose: use functions.