使用IF ELSE编程概念 [英] programming concepts with IF ELSE

查看:159
本文介绍了使用IF ELSE编程概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到如下问题



案例1:

I have a problem like below

CASE 1:

bool flag1= false;
bool flag2= true;

If(flag1 && flag2)
{
}

else
{

}



案例2:


CASE 2:

bool flag1= false;
bool flag2= true;

If(flag1 || flag2)
{
}

else
{

}



两种情况下如何控制if else块。


in both case how control will follow from if else block.

推荐答案

Case1执行 else 块,因为其中一个标志未设置为 true AND 要求所有标志等于 true



Case2执行 if 块,因为其中一个标志设置为 true OR 满足其中一个等于 true 的标志。
Case1 executes the else block, because one of the flags is not set to true. AND requires all flags to equal true.

Case2 executes the if block, because one of the flags is set to true. OR is satisfied with one of the flags equalling true.


您的代码甚至不会编译(您使用 falg1 而不是 flag1 in if expression :-))。

在这两种情况下,执行 else 块是正确的行为,因为操作数之一是 false 。但是有一点点差异(正如 phil.o 正确指出的那样):

  • 在案例1中, flag2 甚至没有评估。
  • 在案例2中, flag1 flag2 被评估
You code won't even compile (you used falg1 instead of flag1 in if expression :-) ).
In both cases, executing the else block is the correct behavior, since one of the and operands is false. However there is a slight difference ( as correctly noted by phil.o):
  • In CASE 1, flag2 is not even evaluated.
  • In CASE 2, both flag1 and flag2 are evaluated


解决方案3的补充:为什么 flag2 甚至没有评估可能很重要吗?



An addition to Solution 3: why "flag2 is not even evaluated" can be important?

static bool Check1() { System.Console.WriteLine("checking condition 1"); return false; }
static bool Check2() { System.Console.WriteLine("checking condition 2"); return true; }

if (Check1() && Check2()) { } // will print only "checking condition 1"

// but 

if (Check1() & Check2()) { } // will print only "checking condition 1" and then "checking condition 2"





因此,使用'&&'而不是'&',优化并在可能的情况下进行冗余检查。不同之处在于布尔操作数中存在副作用



在实践中,我建议:

  • 避免对任何可能导致副作用的布尔函数使用复杂的布尔运算;
  • 如果考虑到上述情况,请选择'&&'和'|| 'over'&'或'|'。

  • 这篇关于使用IF ELSE编程概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆