0或1以外的整数的布尔值是多少? [英] What is the boolean value of integers other than 0 or 1?

查看:401
本文介绍了0或1以外的整数的布尔值是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的函数,根据一组应命名为cam1_0.bmp,cam1_1.bmp的文件来派生新文件名,并进行了尝试.

I was writing a simple function to derive a new filename based on a set of files that should be named as cam1_0.bmp, cam1_1.bmp, and tried this out.

static int suffix = 0;
std::string fPre("cam");
std::ifstream fs;
std::string fName;
do {
    fName = fPre;
    fName.append(std::to_string(camera)).append("_").append(std::to_string(suffix)).append(".bmp");
    fs.open(fName);
} while (fs.good() && ++suffix);

这项工作奏效了,这让我想知道对于0或1以外的数字值,相应的布尔值的标准定义行为是什么.通过此实验,我知道包括0以外的其他负值的所有值都将评估为true.根据标准,仅将0视为假吗?

This works and it made me wonder what is the standard, defined behavior of corresponding boolean values for number values other than 0 or 1. With this experiment I know all values including negative values other than 0 evaluates to true. Is only 0 considered to be false as per the standard?

推荐答案

在C ++中,整数没有布尔值. (不同的语言有不同的规则,但是这个问题是关于C ++的.)

In C++, integers don't have boolean values. (Different languages have different rules, but this question is about C++.)

转换为bool类型的整数值(转换通常是隐式进行的)的结果是明确定义的.将0转换为bool的结果是false;将任何非零值转换为bool的结果是true.

The result of converting an integer value to type bool (a conversion which is often done implicitly) is well defined. The result of converting 0 to bool is false; the result of converting any non-zero value to bool is true.

这同样适用于浮点值(0.0转换为false,所有其他值转换为true)和指针(空指针转换为false,所有非空指针值转换到true).

The same applies to floating-point values (0.0 converts to false, all other values convert to true) and to pointers (a null pointer converts to false, all non-null pointer values convert to true).

这篇关于0或1以外的整数的布尔值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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