|之间的差异和||或&和&&用于比较 [英] Difference between | and || or & and && for comparison

查看:144
本文介绍了|之间的差异和||或&和&&用于比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


与|和||或&和&&

  if(test = = test1 | test1 == test2)或if(test == test1 || test1 == test2)
if(test == test1& test1 == test2)or if(test == test1& test1 == test2)


可能)单个 | & 是按位比较。

double || &&& 是一种逻辑比较。

阅读Mehrdad关于无短路的评论



实际上,由于 true 通常等于 1 false 通常等价于 0 ,按位比较有时可能有效,并且返回完全相同的结果。



曾经有一个任务关键软件组件我运行了静态代码分析器,并指出,在进行逻辑比较时,使用逐位比较。由于它是用C语言编写的,并且由于逻辑比较的安排,软件与任何一个都很好地工作。示例:

  if((altitide> 10000)&(knots> 100))
...


Possible Duplicate:
A clear, layman’s explanation of the difference between | and || in c# ?

What is the difference between comparing with | and || or & and && in C# and Javascript?

Examples:

if(test == test1 | test1 == test2) or if(test == test1 || test1 == test2)
if(test == test1 & test1 == test2) or if(test == test1 && test1 == test2)

解决方案

in C (and other languages probably) a single | or & is a bitwise comparison.
The double || or && is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"

In practice, since true is often equivalent to 1 and false is often equivalent to 0, the bitwise comparisons can sometimes be valid and return exactly the same result.

There was once a mission critical software component I ran a static code analyzer on and it pointed out that a bitwise comparison was being used where a logical comparison should have been. Since it was written in C and due to the arrangement of logical comparisons, the software worked just fine with either. Example:

if ( (altitide > 10000) & (knots > 100) )
...

这篇关于|之间的差异和||或&和&&用于比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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