How is if statement evaluated in c++?

99封情书 提交于 2019-11-26 22:24:31

问题


Is if ( c ) the same as if ( c == 0 ) in C++?


回答1:


No, if (c) is the same as if (c != 0). And if (!c) is the same as if (c == 0).




回答2:


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.




回答3:


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.




回答4:


It'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.




回答5:


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");
}



回答6:


Yes they are the same if you change == 0 to != 0.




回答7:


if(c)
{
  //body
}

The possible value of c are: negative , zero , positive

Conditional statement treat * zero* as false

While for negative and positive it's true

and block will execute only if condition is true.




回答8:


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.



来源:https://stackoverflow.com/questions/1479100/how-is-if-statement-evaluated-in-c

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