Implicit Conversions and Narrowing Casts

Numbers as Booleans

Why does C++ treat non-zero numbers as true and zero as false?

3D art showing a wizard character

This is a really interesting question that goes back to how computers fundamentally work with true and false values. Let's break it down:

The Historical Reason

In early computers, there was no special boolean type - programmers used regular numbers to represent true and false. They needed a consistent rule for which numbers meant true and which meant false. The simplest rule was:

  • 0 means false (nothing, absence of a value)
  • Any other number means true (presence of a value)

This tradition carried forward into C, and then into C++, even after C++ added the bool type.

Why This Makes Sense

This convention actually turns out to be really useful in practice. Here's an example:

#include <iostream>
using namespace std;

int main() {
  int PlayerHealth{100};

  // We can use PlayerHealth directly in an
  // if statement
  if (PlayerHealth) {
    cout << "Player is alive!\n";
  }

  // Later in the game, player takes damage...
  PlayerHealth = 0;

  if (PlayerHealth) {
    cout << "Player is alive!";
  } else {
    cout << "Game Over!";
  }
}
Player is alive!
Game Over!

In this example, we can check if the player is alive just by checking if their health is non-zero. We don't need to write if (PlayerHealth > 0) - though that would work too!

Real World Examples

This pattern shows up in many real-world programming scenarios:

  • Checking if we found something (0 means not found)
  • Checking if a calculation succeeded (0 means failed)
  • Checking if a player has any resources left (0 means empty)
  • Checking if an error occurred (0 means no error)

The pattern is so useful that many modern programming languages have adopted it, even ones that weren't based on C or C++.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved