Ternary operators vs if-else statements

jraleman
jraleman
Jan 7, 2018 · 3 min read
       yes
__ __ __ __
| |
| |
| ^
condition ? true : false
| ^
| |
|__ __ __ __ __ __ __|
no

When to use them?

bool y = (x == 42) ? true : false;
y = "True" if x == 42 else "False"

How about an if-else statement?

bool y;if (x == 42){
y = true;
}
else {
y = false;
}
? -> if (x == 42) {}
y -> true;
: -> else {}
y -> false;
bool y; if (x == 42) {y = true;} else {y = false;}
bool y = (x == 42) ? true : false;

When should I avoid it?

if (x == 42) {
std::cout << "code is executed" << std::endl;
code();
}
else {
std::cout << "nothing happened" << std::endl;
}
(x == 42) ? ((std::cout << "code is executed" << std::endl), code()) : (void)(std::cout << "nothing happened" << std::endl);

Conclusion

jraleman

Written by

jraleman

https://jraleman.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade