Logical equality in C

て烟熏妆下的殇ゞ 提交于 2019-12-04 03:15:31

问题


[It seems odd this doesn't exist, so apologies in advance if it's a duplicate]

I want to test for logical equality in C. In other words, I want to know whether two values would be equal if both were converted in the normal way associated with logical expressions.

In C99, I think that

(bool)a == (bool)b

gives what I want. Is that correct? What is the normal way of writing this in traditional C?


回答1:


You typically see this:

if ((a == 0) == (b == 0))

Or

if (!!a == !!b)

Since !!a evaluates to 1 if a is nonzero and 0 otherwise.

Hope this helps!




回答2:


In C, zero is false. If you want to convert any value to its boolean equivalent, the standard way (well, except that there's almost never a need for it) is to prefix an expression with !! , as in !!a. In the case of your expression, !!a == !!b may be simplified to !a == !b




回答3:


In pre-C99 C, the tradiitional, idiomatic way to "cast to bool" is with !!.




回答4:


There is no (bool) in traditional c. True/False is handled using ints. You can check for boolean equality with

a ? b : !b


来源:https://stackoverflow.com/questions/10952759/logical-equality-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!