Total noob here so be gentle. I've looked everywhere and can't seem to find the answer to this. How do I condense the following?
if (expression) { return true; } else { return false; }
I can't get it to work since it's returning something vs. setting something. I've already seen things like this:
somevar = (expression) ? value1 : value2;
Like I said, please be gentle :)
Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.
Answer: Yes, we can use if-else in one line. In Python, we can convert if-else into one conditional statement.
The if / then statement is a conditional statement that executes its sub-statement, which follows the then keyword, only if the provided condition evaluates to true: if x < 10 then x := x+1; In the above example, the condition is x < 10 , and the statement to execute is x := x+1 .
return (expression) ? value1 : value2;
If value1
and value2
are actually true
and false
like in your example, you may as well just
return expression;
All you'd need in your case is:
return expression;
The reason why is that the expression itself evaluates to a boolean value of true
or false
, so it's redundant to have an if
block (or even a ?:
operator).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With