在 C++ 中如何评估 if 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1479100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How is if statement evaluated in c++?
提问by derrdji
Is if ( c )
the same as if ( c == 0 )
in C++?
是if ( c )
同if ( c == 0 )
在C ++?
回答by Jesper
No, if (c)
is the same as if (c != 0)
.
And if (!c)
is the same as if (c == 0)
.
不,if (c)
是一样的if (c != 0)
。并且if (!c)
与 相同if (c == 0)
。
回答by D.Shawley
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.
我会打破这一包......“ if (c)
”最接近“ if (((bool)c) == true)
”。对于整数类型,这意味着“ if (c != 0)
”。正如其他人指出的那样,重载operator !=
可能会导致一些奇怪的事情,但operator bool()
除非我弄错了,否则重载 " "也会引起一些奇怪的事情。
回答by Patrice Bernassola
If c is a pointer or a numeric value,
如果 c 是指针或数值,
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())
如果 c 是布尔值(类型 bool [仅 C++]),(编辑:或具有运算符 bool() 重载的用户定义类型)
if( c )
is equivalent to
相当于
if( c == true )
If c is nor a pointer or a numeric value neither a boolean,
如果 c 既不是指针也不是数值,也不是布尔值,
if( c )
will not compile.
不会编译。
回答by Mehrdad Afshari
It's more like if ( c != 0 )
它更像是 if ( c != 0 )
Of course, !=
operator can be overloaded so it's not perfectly accurate to say that those are exactly equal.
当然,!=
运算符可以重载,因此说它们完全相等并不完全准确。
回答by galets
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:
这仅适用于数值。如果 c 是类,则必须重载一个运算符来进行布尔值转换,例如此处:
#include <stdio.h>
class c_type
{
public:
operator bool()
{
return true;
}
};
int main()
{
c_type c;
if (c) printf("true");
if (!c) printf ("false");
}
回答by Brian R. Bondy
Yes they are the same if you change == 0
to != 0
.
是的,如果您更改== 0
为 ,它们是相同的!= 0
。
回答by vikash vishwakarma
if(c)
{
//body
}
The possible value of c are: negative , zero , positive
c 的可能值是:negative , zero , positive
Conditional statement treat * zero* as false
条件语句将 * 零 * 视为 false
While for negative and positive it's true
而对于消极和积极,它是 true
and block will execute only if condition is true
.
仅当条件为 时,块才会执行true
。
回答by Troubadour
If c
is a pointer then the test
如果c
是指针,则测试
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.
后者是c
对0
(空)指针的直接检查,而前者实际上是检查是否c
指向有效对象的指令。不过,通常编译器会生成相同的代码。