Rama
Rama

Reputation: 3305

Is there a difference between if (intVar) and if (intVar != 0)?

I'm interested in knowing if there is a difference between these two if blocks in c ++. It would be very useful if with the answer you can cite some reference.

if ( intVar!= 0 )
{
  //Do something
}

and

if (intVar)
{
  //Do samething
}

Where intVar, could be any type of integer variable with any value.

[EDIT] On the subject "duplicated question". I did not find any question about this in which the if statement is involved.

Upvotes: 2

Views: 283

Answers (3)

Smeeheey
Smeeheey

Reputation: 10336

The type of the expression required in the if condition is boolean. The expression intVar!=0 is already boolean, the expression intVar has type int and requires an implicit conversion to boolean. As it happens the conversion rules for int to bool are precisely that anything non-zero maps to true and zero maps to false, so the resultant expression evaluation is exactly the same.

Sometimes writing the full intVar!=0 can add clarity (for example, to make it clear you're not evaluating a pointer type for nullptr but rather an integral type for zero), whereas other times it doesn't - it really depends on the context.

Regarding requested references, I will use the standard. The section relating to conversions [conv.bool]:

4.14 Boolean conversions

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true

Upvotes: 7

YSC
YSC

Reputation: 40090

Additionally to other's answers (and for fun), I'd like to say that for an intVar of a user-defined type defining an implicit conversion operator to int and another to bool, the two expression could have a different behaviour:

#include <iostream>

class Celcius
{
    int _value;
public:
    Celcius(int value) : _value(value) {}
    operator int() { return _value; }
    operator bool() { return _value > -273; }
};

int main()
{
    Celcius waterBoilingPoint(0);

    if (waterBoilingPoint != 0) { // false
        std::cout << "This is not Standard Conditions for Temperature and Pressure!\n";
    }

    if (waterBoilingPoint) { // true
        std::cout << "This is not 0K (pun intended).\n";
    }
}

But this is an edge case I wouldn't jump into.

Upvotes: 5

Jonas K&#246;ritz
Jonas K&#246;ritz

Reputation: 2644

In C++ (and many other languages) there is no difference as any non zero value is "truey" and zero itself is "falsey".

Upvotes: 4

Related Questions