Additionally, there exists a shorthand for if…else statements, referred to as the ternary operator due to its three operands. It’s employed to condense multiple lines of code into a single line and is commonly used to simplify straightforward if…else statements.
variable = (condition) ? expressionTrue : expressionFalse; |
Instead of composing:
int time = 20; if (time < 18) { printf(“Good day.”); } else { printf(“Good evening.”); } |
You can express it simply as:
int time = 20; (time < 18) ? printf(“Good day.”) : printf(“Good evening.”); |
The decision to employ either the traditional if…else statement or the ternary operator is entirely yours to make.