简体   繁体   中英

How to write else if as logical statement?

I want to write an if-else statement as a logical statement. I know that:

if (statement1){
   b=c
}
else{
   b=d
}

can be written as:

b=(statement1 && c)||(!statement1 && d)

But how do I write the following if-else statements as logical?:

if (statement1){
   b=c
}
else if (statement2){
   b=d
}
else{
   b=e
}

I have thought of something like:

b=(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)

I'm sorry if there is already a post about this. I have tried, but couldn't find anything similar to my problem.

As with all logical statement building, it'll be easiest to create a truth table here. You'll end up with:

+--+--+--------+
|s2|s1| result |
+--+--+--------+
| 0| 0|   e    |
+--+--+--------+
| 0| 1|   c    |
+--+--+--------+
| 1| 0|   d    |
+--+--+--------+
| 1| 1|   c    |
+--+--+--------+

So un-simplified, that'll be

(!s1 & !s2 & e) || (!s2 & s1 & c) || (s2 & !s1 & d) || (s1 & s2 & c)

This can be simplified by combining the two c results and removing the s2 :

(!s1 & !s2 & e) || (s2 & !s1 & d) || (s1 & c)

(note that this will be faster in C++ and match the if statements closer with s1 & c as the first term. This will especially make a difference if evaluating any of these values will cause outside effects)


Note that what you built,

(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)

will function incorrectly if statement1 is true, c is false, and both statement2 and d are true (you'll get a result of true when you should have false).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM