C Programming - C Preprocessor - Discussion
Discussion Forum : C Preprocessor - Find Output of Program (Q.No. 10)
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;
}
Answer: Option
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.
Discussion:
4 comments Page 1 of 1.
Vinay guda said:
8 years ago
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)))
#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)))
Ajay said:
1 decade ago
MAX(a, b) (a > b ? a : b). Please can anyone explain how it evaluate value?
Geetha said:
1 decade ago
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.
HERE,
x=max(a>b?a:b). Here a=3+2=5;b=7+2=9.and 9>5.
So the answer is 9.
Wikiok said:
1 decade ago
It is only working because "+" has higher precedence, than "<". It will not work with &,|,^,&&,||.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers