- #1
Raghav Gupta
- 1,011
- 76
Member warned about posting questions that could be easily answered in a web search
What is ternary operator in c++ and its use?
if (i == 10){
return 5;
} else {
return 1;
}
return (i == 10) ? 5 : 1
void printfString(const char * format, const char * str){
printf(format, (str == NULL ? "NULL" : str));
}
double fmax( double a, double b){
return (a > b) ? a : b;
}
JorisL said:I would generally avoid using the ternary operation.
It can make your code hard to read.
// Don't do this.
foo().bar->baz(qux)->quux.quuux->quuuux();
// Don't do this.
(set_a ? a : b) = 42;
// Don't do this.
x = condition_a ?
(condition_b ?
(condition_c ? 0 : 1) : (condition_d ? 2 : 3)) ?
(condition_e ? 4 : 5);
// I can't think of a good example. I like the ternary operator.
//Do this!
std::cout << (success ? "Success!" ? "Failure.") << '\n';
D H said:Never use the ternary operator as an lvalue.Code:// Don't do this. (set_a ? a : b) = 42;
set_a ? (a = 42) : (b = 42);
It is totally legal in C++, even if they aren't references. (The ternary operator in C isn't quite that powerful.)newjerseyrunner said:That's actually illegal unless both a and b are references, this would be the proper way to write that.
A ternary operator in C++ is a conditional operator that takes three operands and evaluates a condition. It is also known as the "conditional operator" or the "inline if statement". It is represented by the symbol "?" and is used to make decisions based on a condition.
The syntax of a ternary operator in C++ is: condition ? expression1 : expression2. The condition is evaluated first, and if it is true, expression1 is executed. If the condition is false, expression2 is executed. The expressions can be any valid C++ expressions, including function calls, variables, or literal values.
The purpose of using a ternary operator in C++ is to write concise and efficient code. It allows us to write conditional statements in a single line of code instead of using multiple lines with if-else statements. It also makes the code more readable and easier to understand.
Yes, a ternary operator can be nested in C++. This means that the expression used in the conditional statement can also be another ternary operator. However, it is recommended to use nested ternary operators sparingly as it can make the code more complex and difficult to read.
Yes, there are a few limitations to using ternary operators in C++. Firstly, the expressions used must be of the same data type. Secondly, they cannot be used for complex conditionals that involve multiple comparisons or logical operators. Lastly, they should not be used for side-effect expressions, as the order of evaluation may not be as expected.