Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical equality in C

[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?

like image 649
andrew cooke Avatar asked Jun 08 '12 16:06

andrew cooke


People also ask

Is === a logical operator?

Comparison operators allow us to assert the equality of a statement with JavaScript. For example, we can assert whether two values or expressions are equal with === , or, whether one value is greater than another with > .

What is a logical condition in C?

We use logical operators to perform various logical operations on any set of given expressions. The logical operators in C are used for combining multiple constraints/ conditions or for complementing the evaluation of any original condition that is under consideration.

What is equality in C?

Both operands of any relational or equality operator can be pointers to the same type. For the equality ( == ) and inequality ( != ) operators, the result of the comparison indicates whether the two pointers address the same memory location.

Is a == b == C valid in C?

How expression a==b==c (Multiple Comparison) evaluates in C programming? Since C language does not support chaining comparison like a==b==c; each equal to operator (==) operates on two operands only.


3 Answers

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!

like image 103
templatetypedef Avatar answered Oct 02 '22 03:10

templatetypedef


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

like image 42
Yusuf X Avatar answered Oct 02 '22 05:10

Yusuf X


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

like image 26
R.. GitHub STOP HELPING ICE Avatar answered Oct 02 '22 05:10

R.. GitHub STOP HELPING ICE