fre*_*low 3 c++ if-statement function-pointers switch-statement control-flow
假设我有两个布尔变量,我想根据它们的值做完全不同的事情.实现这一目标的最简洁方法是什么?
变式1:
if (a && b)
{
// ...
}
else if (a && !b)
{
// ...
}
else if (!a && b)
{
// ...
}
else
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
变式2:
if (a)
{
if (b)
{
// ...
}
else
{
// ...
}
}
else
{
if (b)
{
// ...
}
else
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
变式3:
switch (a << 1 | b)
{
case 0:
// ...
break;
case 1:
// ...
break;
case 2:
// ...
break;
case 3:
// ...
break;
}
Run Code Online (Sandbox Code Playgroud)
变式4:
lut[a][b]();
void (*lut[2][2])() = {false_false, false_true, true_false, true_true};
void false_false()
{
// ...
}
void false_true()
{
// ...
}
void true_false()
{
// ...
}
void true_true()
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
对于普通程序员来说,变体3和4是否过于棘手/复杂?我错过了其他任何变种?
sha*_*oth 13
第一个变体是最清晰,最易读的,但可以调整:
if (a && b) {
// ...
} else if (a) { // no need to test !b here - b==true would be the first case
// ...
} else if (b) { //no need to test !a here - that would be the first case
// ...
} else { // !a&&!b - the last remaining
// ...
}
Run Code Online (Sandbox Code Playgroud)