Is if ( c )
the same as if ( c == 0 )
in C++?
views:
480answers:
7It's more like if ( c != 0 )
Of course, !=
operator can be overloaded so it's not perfectly accurate to say that those are exactly equal.
No, if (c)
is the same as if (c != 0)
.
And if (!c)
is the same as if (c == 0)
.
I'll break from the pack on this one... "if (c)
" is closest to "if (((bool)c) == true)
". For integer types, this means "if (c != 0)
". As others have pointed out, overloading operator !=
can cause some strangeness but so can overloading "operator bool()
" unless I am mistaken.
This is only true for numeric values. if c is class, there must be an operator overloaded which does conversion boolean, such as in here:
#include <stdio.h>
class c_type
{
public:
operator bool()
{
return true;
}
};
int main()
{
c_type c;
if (c) printf("true");
if (!c) printf ("false");
}
If c is a pointer or a numeric value,
if( c )
is equivalent to
if( c != 0 )
If c is a boolean (type bool [only C++]), (edit: or a user-defined type with the overload of the operator bool())
if( c )
is equivalent to
if( c == true )
If c is nor a pointer or a numeric value neither a boolean,
if( c )
will not compile.
If c
is a pointer then the test
if ( c )
is not quite the same as
if ( c != 0 )
The latter is a straightforward check of c
against the 0
(null) pointer whereas the former is actually a instruction to check whether c
is points to a valid object. Typically compilers produce the same code though.