Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the boolean value of integers other than 0 or 1?

Tags:

c++

boolean

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);

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?

like image 253
dev_nut Avatar asked Nov 19 '14 18:11

dev_nut


People also ask

Is a boolean just 1 or 0?

Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.

What is the boolean value of 0?

Boolean Variables and Data Type ( or lack thereof in C )Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

What are the 2 boolean values?

A variable of the primitive data type boolean can have two values: true and false (Boolean literals). or off. Boolean expressions use relational and logical operators. The result of a Boolean expression is either true or false.


1 Answers

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

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.

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).

like image 167
Keith Thompson Avatar answered Nov 15 '22 04:11

Keith Thompson