Other Language Constructs - Tertiary Operator ( ? : )
Published by
sanya sanya
The tertiary operator, also known as the conditional operator, is a shorthand way of expressing a simple if-else statement. It allows you to assign a value or execute an expression based on a condition. The operator consists of a question mark (?) and a colon (:).
Syntax:
condition ? expression1 : expression2
If the condition is true, the value of ‘expression1’ is returned; otherwise, the value of ‘expression2’ is returned. The type of the expressions must be compatible.
Example:
#include
using namespace std;
int main() {
int num1 = 10;
int num2 = 20;
int max = (num1 > num2) ? num1 : num2;
cout << "The maximum number is: " << max << endl;
return 0;
}
Output:
The maximum number is: 20
Applications of the ternary operator:
1. Conditional assignment: It can be used to assign a value to a variable based on a condition without the need for an explicit if-else statement.
2. Compact conditional expressions: It provides a concise way to perform different actions or return different values based on a condition.
Advantages of the ternary operator:
1. Concise syntax: It allows you to write conditional expressions in a single line, which can make the code more readable and compact.
2. Avoids code duplication: It eliminates the need for repetitive if-else statements for simple conditional checks, reducing code duplication.
Disadvantages of the ternary operator:
1. Limited complexity: It is not suitable for complex conditions or multiple actions that require more than two expressions. In such cases, using if-else statements might be more appropriate.
2. Reduced readability for complex expressions: Overusing the ternary operator or writing complex expressions with it can make the code harder to read and understand, especially for others who are not familiar with the code.
Library
WEB DEVELOPMENT
FAANG QUESTIONS