条件检查:if(x == 0)vs.if(!x) [英] Condition checking: if(x==0) vs. if(!x)

查看:185
本文介绍了条件检查:if(x == 0)vs.if(!x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if(x == 0) if(!x)有什么区别?还是它们总是等效的?对于 x 的不同C ++内置类型:

What's the differences of if(x==0) vs. if(!x)? Or are they always equivalent? And for different C++ build-in types of x:


  • bool

  • int

  • char

  • 指针

  • iostream

  • ...

  • bool
  • int
  • char
  • pointer
  • iostream
  • ...

推荐答案

假定从类型到支持 if(x) if(!x)的内容进行了转换,那么只要 operator int() opterator bool(),结果将相同。

Assuming there is a conversion from a type to something that supports if (x) or if (!x), then as long as there isn't a DIFFERENT conversion for operator int() than opterator bool(), the result will be the same.

如果(x == 0)将使用最佳转换,其中包括 bool void * 转换器。只要有任何可以将类型转换为标准类型的转换器。

if (x == 0) will use the "best" conversion, which includes a bool or void * converter. As long as there is any converter that can convert the type to some "standard type".

if(!x)会完全一样,它将使用任何转换为​​标准类型的转换器。

if(!x) will do exactly the same, it will use any converter that converts to a standard type.

这两个当然都假定转换器功能不是C + +11不默认转换。

Both of these of course assume the converter function isn't a C++11 "don't default convert".

当然,如果您有这样的课程:

Of course, if you have a class like this:

class
{
   int x;
  public:
   bool operator bool() { return x != 0; }
   int operator int() { return x == 0; } 
}; 

然后 if(x == 0)将执行 if((x == 0)== 0) if(!x)将执行 if(!(x!= 0),这是不一样的。但是现在我们真的很想麻烦,这是非常糟糕的设计代码。

then if (x == 0) will do if ( (x == 0) == 0) and if (!x) will will do if (! (x != 0), which isn't the same. But now we're really TRYING to make trouble, and this is VERY BADLY designed code.

当然,上面的示例可能会导致任何 operator int()错误 false 表示 x == 0 true 值。

Of course, the above example can be made to go wrong with any operator int() that doesn't result in false for x == 0 and true for all other values.

这篇关于条件检查:if(x == 0)vs.if(!x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆