Cpp - Use int as boolean in if statement

Introduction

In C++, the value 0 also is considered false and any other value is true.

C++ takes advantage of this feature in if statements:

if (my_int) 
    std::cout << "There are " << x << " my_int left\n"; 

When my_int equals 0, the if expression is false and the count is not displayed.

When my_int is any other number, the expression is true and the count is shown. This code is the same as the following:

if (my_int != 0) 
    std::cout << "There are " << x << " my_int left\n"; 

Both statements are permitted in C++, but the latter is clearer.

These two statements are equivalent: 
if (!x) 
if (x == 0) 

Both statements are true when x equals 0. The second statement is somewhat easier to comprehend.

Related Example