简体   繁体   English

为什么将一个int转换为bool会发出警告?

[英]Why does casting an int to a bool give a warning?

Shouldn't it be ok to use static_cast to 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);

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 int to bool and it makes the code much more readable (because it makes the assumptions explicit). 这是将int转换为bool的唯一逻辑上正确的方法,它使代码更具可读性(因为它使假设明确)。

The same applies for the reverse, by the way. 顺便提一下,这同样适用于相反的情况。 Converting implicitly from bool to int is just lazy. bool隐式转换为int只是懒惰。 Make the mapping explicit: 使映射显式:

int result = condition ? 1 : 0;

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 , 对bool的隐含转换也有点争议:在调用malloc ,很多人喜欢if (buf != NULL)或者if (buf != 0)优先于if (buf)
  • the comparison is both shorter and clearer. 比较既简短又清晰。

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. 这绝不会发出警告。

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更直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM