C++ 为什么将 int 转换为 bool 会发出警告?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4968033/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:02:49  来源:igfitidea点击:

Why does casting an int to a bool give a warning?

c++visual-c++castingbooleancompiler-warnings

提问by user4344

Shouldn't it be ok to use static_castto convert int to bool as it converts reverse of implicit conversion but i still get a warning?

使用static_cast将 int 转换为 bool 是不是应该可以,因为它转换了隐式转换的反向但我仍然收到警告?

Example:

例子:

MSVC++ 8

MSVC++ 8

bool bit = static_cast<bool>(100);

回答by Konrad Rudolph

Just because the conversion a => b is implicit doesn't say anything about the viability of the reverse, b => a.

仅仅因为转换 a => b 是隐式的,并没有说明反向的可行性,b => a。

In your case, you shouldn't cast at all. Just do the obvious thing: compare:

在你的情况下,你根本不应该投。做显而易见的事情:比较:

bool result = int_value != 0;

This is the only logically correct way of converting an intto booland it makes the code much more readable (because it makes the assumptions explicit).

这是将 an 转换为intto的唯一逻辑正确的方法,bool它使代码更具可读性(因为它使假设明确)。

The same applies for the reverse, by the way. Converting implicitly from boolto intis just lazy. Make the mapping explicit:

顺便说一下,这同样适用于相反的情况。从bool到隐式转换int只是懒惰。使映射明确:

int result = condition ? 1 : 0;

回答by Steve Jessop

That's between you and your compiler, but Microsoft thinks you should write:

那是你和你的编译器之间的,但微软认为你应该写:

i != 0

in preference to either:

优先于:

(bool)i

or

或者

static_cast<bool>(i)

Possible reasons for preferring it include:

偏爱它的可能原因包括:

  • this conversion doesn't act like other narrowing conversions, that take a modulus,
  • the implict conversions to bool are also a bit controversial: plenty of people prefer to do if (buf != NULL)or if (buf != 0)in preference to if (buf)after a call to malloc,
  • the comparison is both shorter and clearer.
  • 这种转换不像其他缩小转换那样,需要一个模数,
  • 对 bool 的隐式转换也有点争议:很多人更喜欢 doif (buf != NULL)或更喜欢if (buf != 0)if (buf)调用后malloc
  • 比较既简短又清晰。

回答by sashoalm

I'm not sure why it happens when you explicitly cast it (i think it was a performance warning?), but I usually use code like this to avoid any warnings:

我不确定为什么当你明确地投射它时会发生它(我认为这是一个性能警告?),但我通常使用这样的代码来避免任何警告:

int i;
bool b = (0!=i);

This never gives warnings.

这永远不会发出警告。

回答by seth

I do as someone already posted:

我按照已经发布的人做的:

bool result = int_value != 0;

It's the easier way imo and the it's more intuitive than trying to cast the integer to bool.

这是imo更简单的方法,而且比尝试将整数转换为bool更直观。