c++ 中的 if 语句如何计算?

发布于 2024-08-06 09:40:19 字数 69 浏览 2 评论 0原文

if ( c ) 与 C++ 中的 if ( c == 0 ) 相同吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

冷心人i 2024-08-13 09:40:19

不,if (c)if (c != 0) 相同。
if (!c)if (c == 0) 相同。

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

歌入人心 2024-08-13 09:40:19

我将在这个问题上打破常规......“if (c)”最接近“if (((bool)c) == true)” 。对于整数类型,这意味着“if (c != 0)”。正如其他人指出的那样,重载 operator != 可能会导致一些奇怪的情况,但重载“operator bool()”也会导致一些奇怪的情况,除非我弄错了。

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.

一瞬间的火花 2024-08-13 09:40:19

如果 c 是指针或数值,

if( c )

则相当于

if( c != 0 )

如果 c 是布尔值(类型 bool [仅限 C++]),
(编辑:或具有运算符 bool() 重载的用户定义类型)

if( c )

相当于

if( c == true )

如果 c 不是指针或数值,也不是布尔值,

if( c )

则不会编译。

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.

み零 2024-08-13 09:40:19

它更像是 if ( c != 0 )

当然,!= 运算符可以重载,因此说它们完全相等并不完全准确。

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.

ˉ厌 2024-08-13 09:40:19

这仅适用于数值。如果 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");
}

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");
}
爱,才寂寞 2024-08-13 09:40:19

是的,如果将 == 0 更改为 != 0,它们是相同的。

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

撕心裂肺的伤痛 2024-08-13 09:40:19

如果c是一个指针,那么测试

if ( c )

与下面的测试不太一样,

if ( c != 0 )

后者是针对0(空)指针直接检查c而前者实际上是一条检查c是否指向有效对象的指令。通常编译器会生成相同的代码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文