可以确定0为假,1为真吗? [英] Is it ok to assume 0 is false and 1 is true?

查看:298
本文介绍了可以确定0为假,1为真吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过代码是根据int变量而不是bool评估条件的。

I've seen code where a condition is evaluated based on an int variable instead of bool.

int condition
cin >> condition;
if (!condition)
    //do something 

我知道C ++支持0为false和1为true,但这是安全代码吗?是否所有标准的C ++编译器都支持它?

I know that C++ supports that 0 is false and 1 is true, but is this safe code? Is it supported by all C++ compilers as a standard?

考虑到您可能会切换到另一种语言并发现这种代码不是

Could it also be a bad practice considering that you might switch to another language and find out that this kind of code isn't supported?

我的意思是,这是一种很好的做法吗?

I mean, is it good practice at all?

推荐答案

是的,做这个假设是安全的。该标准定义了各种原语到 bool 的隐式转换,所有数字类型基本上都表示 0 转换为 false 和任何非零值都将转换为 true

Yes it is safe to make that assumption. The standard defines the implicit conversion of various primitives to bool, and all the numeric types basically state that 0 converts to false and any non-zero value converts to true.

这篇关于可以确定0为假,1为真吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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