Booleans - true and false values

Not Operator vs Equals False

When should I use ! versus == false when checking if a boolean is false?

3D art showing a wizard character

There are two ways to check if a boolean is false in C++, and while they give the same result, one is generally preferred. Let's explore both approaches and understand why one is better.

The Two Approaches

Here's a comparison of both methods:

#include <iostream>
using namespace std;

int main() {
  bool isAlive{false};

  // Method 1: Using the ! operator
  if (!isAlive) {
    cout << "Not alive (using !)\n";
  }

  // Method 2: Comparing with == false 
  if (isAlive == false) {
    cout << "Not alive (using == false)";
  }
}
Not alive (using !)
Not alive (using == false)

Why ! is Preferred

The ! operator is preferred for several reasons:

  • It's shorter and cleaner to write
  • It's faster to read and understand
  • It's less prone to typing mistakes
  • It's more idiomatic (experienced C++ programmers expect to see it)

Here's an example showing how ! can make complex conditions more readable:

#include <iostream>
using namespace std;

int main() {
  bool isAlive{true};
  bool hasWeapon{false};
  bool isInCombat{true};

  // Using == false makes the code longer and
  // harder to read
  bool cannotFight{
    isAlive == false || hasWeapon == false
    || isInCombat == false};

  // Using ! is cleaner and more readable
  bool cannotFightBetter{
    !isAlive || !hasWeapon || !isInCombat}; 

  cout << "Cannot fight: " << cannotFightBetter;
}
Cannot fight: true

Common Mistakes to Avoid

Be careful not to accidentally use assignment (=) instead of comparison (==):

#include <iostream>
using namespace std;

int main() {
  bool isAlive{false};

  // This is a common mistake - we're not
  // testing isAlive, we're updating it!
  if (isAlive = false) {
    cout << "This will not print because"
      " = assigns false to isAlive\n";
  }

  // Using ! avoids this potential error
  if (!isAlive) {
    cout << "This is clearer and safer";
  }
}
This is clearer and safer

The ! operator makes this kind of mistake impossible, which is another reason it's preferred.

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