dev_nut
dev_nut

Reputation: 2542

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

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?

Upvotes: 6

Views: 18558

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263307

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

Upvotes: 18

locho
locho

Reputation: 49

Yes, any number other than 0 is considered as true for boolean.

Visit http://www.vbforums.com/showthread.php?405047-Classic-VB-Why-is-TRUE-equal-to-1-and-not-1 for some explanation.

Upvotes: 3

Dave
Dave

Reputation: 10924

The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.

Source

Upvotes: 4

Related Questions