Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner if statements, how to convert this if-else-statement

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 :)

like image 747
snickered Avatar asked Jan 07 '11 04:01

snickered


People also ask

What is the replacement of if-else statement?

Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.

Can we write else if statement into one line in Python?

Answer: Yes, we can use if-else in one line. In Python, we can convert if-else into one conditional statement.

What's an example of an if/then else 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 .


2 Answers

return (expression) ? value1 : value2; 

If value1 and value2 are actually true and false like in your example, you may as well just

return expression; 
like image 114
James McNellis Avatar answered Sep 19 '22 05:09

James McNellis


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).

like image 24
Jacob Avatar answered Sep 18 '22 05:09

Jacob