c – 基于两个布尔变量的分支
发布时间:2020-12-16 10:45:55 所属栏目:百科 来源:网络整理
导读:假设我有两个布尔变量,我想根据它们的值做完全不同的事情.实现这一目标的最简洁方法是什么? 变式1: if (a b){ // ...}else if (a !b){ // ...}else if (!a b){ // ...}else{ // ...} 变式2: if (a){ if (b) { // ... } else { // ... }}else{ if (b) { //
假设我有两个布尔变量,我想根据它们的值做完全不同的事情.实现这一目标的最简洁方法是什么?
变式1: if (a && b) { // ... } else if (a && !b) { // ... } else if (!a && b) { // ... } else { // ... } 变式2: if (a) { if (b) { // ... } else { // ... } } else { if (b) { // ... } else { // ... } } 变式3: switch (a << 1 | b) { case 0: // ... break; case 1: // ... break; case 2: // ... break; case 3: // ... break; } 变式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() { // ... } 对于普通程序员来说,变体3和4是否过于棘手/复杂?我错过了其他任何变种? 解决方法
第一个变体是最清晰,最易读的,但可以调整:
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 // ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |