Raghav Gupta
- 1,010
- 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.