Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is this test right: if(obj1.type == obj2.type == 1)?

Tags:

c

c#

objective-c

is this test right: if(obj1.type == obj2.type == 1) and what does it do actually? I'm wondering if this imply some && in the condition or not.

like image 244
Nicolas Manzini Avatar asked Jan 15 '14 10:01

Nicolas Manzini


2 Answers

In C and Objective-C, groups of == operators are evaluated left-to-right, and produce a zero or a one result. Because of this, your expression is the same as

 if(obj1.type == obj2.type)

In C# this produces an error, because == operator cannot be applied to operands of type bool and int.

If you would like to say "if both obj1.type and obj2.type equal 1", you need to use two separate == conditions, and put a logical "AND" operator between them:

if(obj1.type == 1 && obj2.type == 1)
like image 115
Sergey Kalinichenko Avatar answered Oct 31 '22 23:10

Sergey Kalinichenko


Instead of using above test condition, you can change it into:

    if((obj1.type == obj2.type) && (obj2.type== 1))

or you can try changing it to::

    if((obj1.type == 1) && (obj2.type== 1))

For difference between both:

&& operator

&& operates on boolean operands only. It evaluates its first operand. If the result is false, it returns false. Otherwise, it evaluates and returns the results of the second operand. Note that, if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical conjunction performed by the & operator. This is an example of Short Circuit Evaluation.

== Operator

For arguments of value type, the operator == returns true, if its operands have the same value, false otherwise. For the string type, it returns true, if the strings' character sequences match. For other reference types (types derived from System.Object), however, a == b returns true only if a and b reference the same object.

like image 43
Charles Stevens Avatar answered Nov 01 '22 00:11

Charles Stevens