-3

I am learning C in depth. But I am not getting this program. Somebody, please tell me how the output of the below program is m=2, n=3

#include <stdio.h>
#define MAX(a,b) a>b ? a:b
int main()
{
    int m,n;
    m=3+MAX(2,3);
    n=2*MAX(3,2);
    printf("m=%d, n=%d\n",m,n);
    return 0;
}
Lich King
  • 31
  • 1
  • 6

2 Answers2

6

This is why parenthesis in macro definitions are important.

A macro does simple text substitution. So when you do this:

m=3+MAX(2,3);

It expands to this:

m=3+2>3 ? 2:3

With the implicit parenthesis:

m = ((3+2)>3) ? 2:3

Which is probably not what you want.

You need to put parenthesis around the entire macro as well as around each argument wherever it is used:

#define MAX(a,b) ((a)>(b) ? (a) : (b))

This will then expand to:

m = 3 + ((2)>(3) ? (2):(3))

Also note that with a macro like this you open yourself up to side effects of one of the operands. For example, if you did this:

int a=2, b=3;
m = MAX(a++,b);

You would get:

int a=2, b=3;
m = ((a++) > (b) ? (a++) : (b));

This invokes undefined behavior because it attempts to modify a more than once in an expression without a sequence point.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

This is what happens in your case:

int main() {
    int m,n;
    m=3+2>3 ? 2:3; //(3+2)>3 ? 2 : 3 = 2
    n=2*3>2 ? 3:2; //(2*3)>2 ? 3 : 2 = 3
    printf("m=%d, n=%d\n",m,n);
    return 0;
}

If you rewrite your defined to #define MAX(a,b) ((a)>(b) ? (a):(b))

then you will have desired output as it will be evaluated to:

//Correct way with parenthesis
int main() {
    int m,n;
    m=3+((2)>(3) ? (2):(3)); //6
    n=2*((3)>(2) ? (3):(2)); //6
    printf("m=%d, n=%d\n",m,n);
    return 0;
}
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40