C++ ternary operator
Created By: chatGPT
In C++, the ternary operator is a concise way to perform conditional checks and assign values based on those checks. The syntax for the ternary operator is structured as follows:
condition ? expression_if_true : expression_if_false;
Here, condition
is evaluated first. If it's true, the operator evaluates and returns expression_if_true
; if it's false, it evaluates and returns expression_if_false
. This can replace simple if-else statements, helping to make the code cleaner.
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
// max will be 20 because b is greater than a
You can also use the ternary operator for function calls or more complex expressions. Here’s an illustration:
int num = 5; std::string result = (num % 2 == 0) ? "Even" : "Odd";
In this example, the variable result
will be set to "Odd" since num
is not even.
int num = 5;
std::string result = (num % 2 == 0) ? "Even" : "Odd";
// result will be "Odd"
Nesting the ternary operator is also possible, allowing multiple conditions to be checked in a single statement. However, it is important to note that excessive nesting can lead to decreased code readability. Here’s an example of nested usage:
int marks = 85; std::string grade = (marks >= 90) ? "A" : (marks >= 75) ? "B" : "C";
In this case, if marks
is greater than or equal to 90, grade
will be "A"; if not, and if marks
is greater than or equal to 75, grade
will be "B"; otherwise, it will be "C".
int marks = 85;
std::string grade = (marks >= 90) ? "A" : (marks >= 75) ? "B" : "C";
// grade will be "B"