问题
I'm looking for a control structure to deal with potentially multiple blocks of code or a NONE block. The most basic case is when there are only two conditions, A and B:
+-------+-------+------------+
| A | B | Blocks Run |
+-------+-------+------------+
| false | false | C |
| false | true | B |
| true | false | A |
| true | true | A + B |
+-------+-------+------------+
The best thing I have so far is:
if( A )
{
// Run Block A
}
if( B )
{
//Run Block B
}
else if( !A )
{
//Run Block C
}
回答1:
For clarity, I'm going to rename your conditions P and Q (as is the convention in propositional logic)
if( P || Q)
{
P && A();
Q && B();
}
else
{
C();
}
Edit:
adding more checks is rather easy:
if( P || Q || R || S)
{
P && A();
Q && B();
R && D();
S && E();
}
else
{
C();
}
Edit, after comment:
Well how about this.
int runC = 1;
P && (runC=0, A());
Q && (runC=0, B());
R && (runC=0, D());
S && (runC=0, E());
runC && C();
回答2:
If it's all about minimising comparsions using a table is the only way to go.
switch ((B << 1) | A)
{
case 0:
// C
break;
case 0b01: // case 1:
// A
break;
case 0b10: // case 2:
// B
break;
case 0b11: // case 3:
// A
// B
break;
default:
// Shouldn't arrive here.
break;
}
回答3:
If you just want to evaluate each condition once:
if (a) {
A();
if (b) {
B();
}
} else if (b) {
B();
} else {
C()
}
I don't think it's much better than your code, though. While it does evaluate the condition only once, the code blocks to execute are now duplicated. As far as I can see, you'll either have to evaluate a condition twice or a write a code block twice. In that case, I'd prefer evaluating the conditions and saving them to variables, then go with your example: duplicating blocks of code is worse than reading a variable twice (most of the time, it's more important to have code that you can understand and maintain instead of trying to "optimize" it when you haven't measured that it's a bottleneck).
回答4:
You want to run block A when condition A, followed by block B when condition B and so on. With one exception: When no criteria is met then execute the NONE block. Right? Then:
if( !A && !B && !C && ...)
{
run NONE-BLOCK;
}
else
{
if( A ) run A-BLOCK;
if( B ) run B-BLOCK;
if( C ) run C-BLOCK;
...
}
来源:https://stackoverflow.com/questions/21627707/run-a-and-then-b-or-run-c