Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how will ternary operator work

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

2 Answers

0 votes
answered Jun 17, 2020 by LiOS (6,240 points)
edited Jun 19, 2020 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, 2020 by Peter Minarik (25,430 points)
edited Jun 18, 2020 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, 2020 by LiOS (6,240 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, 2020 by Rahul Choubey (550 points)
edited Jun 18, 2020 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.
...