I have seen someone wrote this code #define MAX(x, y) ((x) > (y) ? (x) : (y))
What does it mean?
Asked
Active
Viewed 162 times
0

Alexzhang
- 99
- 6
-
1What's not to understand? If x is larger than y, then the maximum is x, otherwise it's y. Is it the ternary operator or the #define you don't understand? (And why all those brackets?) – Dominique May 01 '21 at 10:14
-
Does this answer your question? [How do I use the conditional (ternary) operator?](https://stackoverflow.com/questions/392932/how-do-i-use-the-conditional-ternary-operator) – Paul Hankin May 01 '21 at 10:14
2 Answers
3
Here it checks if x
is greater than y
if yes then x
else y
.
Let's look at a example to understand it
int max = x > y ? x : y
It simply means
if (x > y)
max = x
else
max = y

Linux Geek
- 957
- 1
- 11
- 19
1
The Ternary Operator is syntactic sugar of writing if-else. You can see this as ( expression )? (result to be stored if true): (result to be stored if false)
. So to answer your question #define MAX(x, y) ((x) > (y) ? (x) : (y))
returns x if x is greater than y else returns y.
EDIT: Changed reference link, and rephrased the sentences.

Manikishan
- 23
- 6
-
1It's called the conditional operator, not the ternary operator. You should have linked the page you linked. – ikegami May 01 '21 at 10:49
-
1“Return” generally means that a statement returns from a function call. This is a misleading term to use when discussion an expression. An operator has a result value or produces a result or evaluates to a result. It does not return a value. – Eric Postpischil May 01 '21 at 11:27
-
1Thanks, I changed the link. I remember reading it as "ternary" or "conditional" operator hence I used the word. And @EricPostpischil thanks for the clarification on return, will change it. – Manikishan May 02 '21 at 09:31