Another conditional statement that allows you to control the flow of the program is ternary operator. Syntax:
There are three operands here. In the condition
, we pass bool value. If the condition
is true, then the statement1
is executed, otherwise statement2
is executed. Example:
Here we have a condition number1 > number2
which returns true or false. If the condition is true, then the value after the question mark (?) will be written to the result
variable, otherwise value after colon (:).
Does anything remind you of a ternary operator? It’s a if/else statement🙂.
So the ternary operator is just shorthand for if/else. Example above using if/else looks like this:
Here we did without the result
variable, but the ternary operator returns a value and it must be written to a variable.
Nested Ternary Operator
The ternary operator can be nested, as well as if/else statements:
With if/else statements, we could write it like this:
Previous article -> 2.11 if else Statements
Next article -> 2.13 Loops
Join to our community in Telegram — https://t.me/itifico
If you want to support me, you can buy me a cup of coffee and I will drink it when I write the next article :)
Donations list:
- Dinesh Chintalapudi — 3$
- Unknown — 5$
- Neisy — 3$
- Unknown — 3$