Variables, Types and Operators

Implicit casts between booleans and numbers in C++

The lesson mentions that numeric types can be implicitly cast to booleans in C++, with 0 being false and anything else true. Can you clarify how that works with an example?

Abstract art representing computer programming

Certainly! In C++, numeric types like int and float can be implicitly converted to the bool type. When this happens:

  • The numeric value 0 (or 0.0, 0.0f, etc.) becomes false
  • Any non-zero numeric value becomes true

Here's an example:

#include <iostream>

int main() {
  bool value1 = 0;
  bool value2 = 1;
  bool value3 = -5;
  bool value4 = 0.0;
  bool value5 = 0.1f;

   // Prints bools as true/false instead of 1/0
  std::cout << std::boolalpha;

  std::cout << value1 << '\n';  // Outputs false
  std::cout << value2 << '\n';  // Outputs true
  std::cout << value3 << '\n';  // Outputs true
  std::cout << value4 << '\n';  // Outputs false
  std::cout << value5 << '\n';  // Outputs true
}
false
true
true
false
true

As you can see, the integer values 1 and -5 both evaluate to true, because they are non-zero. The integer 0 and the floating point 0.0 both evaluate to false.

The opposite is also possible (though less common). true implicitly converts to the integer value 1, and false converts to 0.

This implicit conversion allows us to use the result of boolean expressions in arithmetic operations. But it's generally clearer to avoid this and keep arithmetic and boolean logic separate.

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

A computer programmer
Part of the course:

Professional C++

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

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% 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