how will ternary operator work

+1 vote
asked Jun 17 by Karpaga Vinayagar Tractors (140 points)

2 Answers

0 votes
answered Jun 17 by LiOS (5,280 points)
edited Jun 19 by LiOS
The ternary operator is another way of representing a series of if, else if, else statements depending on the level you need.

Instead of going,

if()

...

else

...

you can go (general syntax view)

value = <condition> ? <true-case> : <false-case>

A basic example in C:

int a = 10;

int b = 20;

int max = a > b ? a : b;

Above is basically saying, if a greater than b ? return value a else return b. In this case it would return b
commented Jun 18 by Peter Minarik (12,220 points)
edited Jun 18 by Peter Minarik
I prefer the "<condition> ? <true-case> : <false-case>" syntax, but good explanation either way. :)

Maybe to extend on it a bit more: why would one use the ternary operator over the if-then-else?

Usually, ternary operators come in handy for short evaluation when we want to use a different value based on some condition.

If one needs to do complex true/false cases depending on the condition(s), then an if-then-else operator is easier to use and read.
commented Jun 18 by LiOS (5,280 points)
Agree completely. A lot of code in C I've coded, I've used if, else if, else statements since they are much easier to read, document and maintain for other developers and much more extendable e.g. want another condition but not using a switch statement, add another else if.

While, as you said, ternary operators are better for short evaluation etc.
0 votes
answered Jun 18 by Rahul Choubey (480 points)
edited Jun 18 by Rahul Choubey
In Python, there is a more legible syntax: var = true_value if condition else false_value. And it’s stackable, so a if b else c if d else e is perfectly good syntax and is the same as a if b else (c if d else e).
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...