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

查看:26
本文介绍了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 以外的负值)都评估为真.按照标准,只有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)和指针(a空指针转换为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天全站免登陆