How to read this if statement?

• 11-25-2011, 11:20 AM
jeroenvanveghel
How to read this if statement?
I have encountered an if-statement in a way I'm unfamiliar with.
After some googling I can't find a answer that's why I'm asking it here.

boolean onlyNots;
Long bonnr;

return ( onlyNots ? bonnr==0 : bonnr != 0 );

Can anyone explain to me what the '?' and the ':' means? And how I'm supposed to read this statement?
When does it return true, when does it return false?

Many thanks in advance!
• 11-25-2011, 12:09 PM
JosAH
Re: How to read this if statement?
It's a ternary expression; its general form is <condition>?<if_true>:<if_false>; if <condition> is true then the value of the entire expression is <if_true>, otherwise the value is <if_false>. In your example the value of the entire expression depends on onlyNots; if it is true the value of the entire expression is bonnr==0 (that is either the value true or false); if the value of onlyNots is false the value of the entire expression is bonnr != 0 (which is also true or false. The return statement could've been written as:

Code:

```if (onlyNots)   return bonnr == 0; else   return bonnr != 0;```
kind regards,

Jos
• 11-25-2011, 12:30 PM
jeroenvanveghel
Re: How to read this if statement?
Thank you for the nice explanation, I'm understanding it now!
• 11-26-2011, 06:30 PM
Iron Lion
Re: How to read this if statement?
Alternatively, the expression could simply have been replaced with:

Code:

`return onlyNots == (bonnr == 0);`
• 11-26-2011, 06:47 PM
JosAH
Re: How to read this if statement?
Quote:

Originally Posted by Iron Lion
Alternatively, the expression could simply have been replaced with:

Code:

`return onlyNots == (bonnr == 0);`

That is 'simply' after a Karnaugh map has been scrutinized and solved ;-)

kind regards,

Jos
• 11-26-2011, 07:05 PM
Mr777
Re: How to read this if statement?
It's also called the Conditional expression, and it behaves as simple if-else. As well defined by JosaH, it has three parts so it's called ternary condition or ternary operator.
It's general syntax is
Code:

`(condition)?TruePart:FalsePart;`