C Programming - C Preprocessor - Discussion

10. 

What will be the output of the program?

#include<stdio.h>
#define MAX(a, b) (a > b ? a : b)

int main()
{
    int x;
    x = MAX(3+2, 2+7);
    printf("%d\n", x);
    return 0;
}

[A]. 8
[B]. 9
[C]. 6
[D]. 5

Answer: Option B

Explanation:

The macro MAX(a, b) (a > b ? a : b) returns the biggest value of the given two numbers.

Step 1 : int x; The variable x is declared as an integer type.

Step 2 : x = MAX(3+2, 2+7); becomes,

=> x = (3+2 > 2+7 ? 3+2 : 2+7)

=> x = (5 > 9 ? 5 : 9)

=> x = 9

Step 3 : printf("%d\n", x); It prints the value of variable x.

Hence the output of the program is 9.


Wikiok said: (Apr 9, 2011)  
It is only working because "+" has higher precedence, than "<". It will not work with &,|,^,&&,||.

Geetha said: (Feb 13, 2013)  
In this program,(a > b ? a : b) is replaced by MAX(a, b), because in macros template is replace by macro expansion.

HERE,

x=max(a>b?a:b). Here a=3+2=5;b=7+2=9.and 9>5.

So the answer is 9.

Ajay said: (Jul 22, 2013)  
MAX(a, b) (a > b ? a : b). Please can anyone explain how it evaluate value?

Vinay Guda said: (Jun 28, 2017)  
Correct way to write this macro to avoid problems related to precedence is,
#define MAX(a,b) ((a)>(b)?(a):(b))

If you write this way you wont face problems when nest MAX.
ie., MAX(a,MAX(b,MAX(c,d)))

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.