1

I was in a lecture and on the power point slides states that true would return 0 and false would return 1. I stated that in Visual Studio anything non zero is considered true, but is there a C++ standard that defines 0 as true?

Visual studio's results were disregarded as non standard but I doubt that it is.

bool tru = true; // returns 0
bool fal = false; // returns 1
Joshua Waring
  • 619
  • 7
  • 23

2 Answers2

5

Absolutely not. From the C++14 working draft (chosen here because I was able to find it easily, not because it's specific to C++14):

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf §4.5.6 (page 85)

Indeed, this behavior is common to most programming languages. Off the top of my head, for instance, Perl, Python, PHP, and Javascript all treat 0 as false and nonzero values as true. The only situation I can think of where 0 is "true" is in UNIX shell scripting, where an exit code of 0 is used for success and nonzero values are used for errors.

2

As mentioned in the accepted answer here, true is defined by the standard to compare equal to 1, and false to 0:

(§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157