Ternary Operators also known as conditional expressions are an elegant and succinct method to replace if-else statement in programming. These operators evaluate something based on a condition being true or not.
In this post, We'll see the different syntax in which ternary operators in implemented in C++, Python and JavaScript.
Consider the following code snippet,
num = int(input('Enter a number please: '))
if num % 2 == 0:
print('num is even')
elif:
print('num is odd')
This code checks if the inputted number is even or odd.
With ternary operator, we can reduce the above if else statements with a one-liner code.
In Python,
# syntax
# [on_true] if [expression] else [on_false]
num = int(input('Enter a number please: '))
print('num is even') if num % 2 == 0 else print('num is odd')
In C++
// syntax
// expression ? [on_true] : [on_false]
int num;
cout << "Please Enter a number: " << endl;
cin >> num;
num % 2 == 0 ? cout << "Num is even" : cout << "num is odd";
In JavaScript
// same syntax as C++
// expression ? [on_true] : [on_false]
let num = prompt('Please Enter a number: ')
num % 2 == 0 ? alert('num is even') : alert('num is odd')
Thus, if the expression to be evaluated is small, then ternary operators can prove to be a viable one-liner alternative.
Top comments (1)
in C++ you can use:
cout << (num%2 == 0 ? "Num is even" : "num is odd");