Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 171 ยท Operators

Comparison and Logical Operators

Compare values in C++ with == != < > <= >=, use the C++20 three-way comparison <=>, and combine conditions with &&, || and ! using short-circuit evaluation.

Every decision a program makes comes down to a question with a yes-or-no answer. Is the password long enough? Is the player still alive and has time left? Is this version newer than that one? In C++ you ask those questions with comparison operators, which produce a bool, and you combine the answers with logical operators.

This lesson covers the six classic comparisons, the pitfalls of comparing signed with unsigned values and floating-point numbers, the three-way comparison operator <=> that C++20 added (nicknamed the spaceship), and the logical operators &&, || and !, including short-circuit evaluation, which lets one condition guard another.

The six comparison operators

Operator Question 5 ? 3
== equal? false
!= not equal? true
< less than? false
> greater than? true
<= less than or equal? false
>= greater than or equal? true

Each comparison yields a bool: true or false. You can store it in a variable, print it, or use it directly in an if or a loop. std::println prints a bool as the words true and false. With std::cout it prints 1 and 0 unless you add std::boolalpha.

C++ Comparing numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Before comparing, C++ applies the same conversions as for arithmetic (see Arithmetic Operators): price < budget converts the int to double, and characters are compared by their numeric codes, so 'B' < 'C' is true but 'a' < 'B' is false, because lowercase letters come after uppercase ones in ASCII.

= assigns, == compares. if (age = 18) sets age to 18 and is always true. Compilers warn about it with -Wall, so keep warnings on and read them.

Signed versus unsigned: the comparison that lies

When you compare a signed integer with an unsigned one of the same size, the signed value is converted to unsigned first. A negative number becomes huge, so the answer is wrong:

C++
int temperature = -1;
unsigned int limit = 10;
bool colder = temperature < limit;   // false! -1 becomes 4294967295

GCC warns about this with -Wall (comparison of integer expressions of different signedness). It happens most often with .size(), which returns an unsigned std::size_t. C++20 added safe comparison functions in <utility> that compare the actual mathematical values, whatever the signedness: std::cmp_equal, std::cmp_not_equal, std::cmp_less, std::cmp_greater, std::cmp_less_equal and std::cmp_greater_equal.

C++ Safe comparisons with std::cmp_less

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Floating-point equality

Because most decimal fractions can't be stored exactly in binary, 0.1 + 0.2 == 0.3 is false. Compare computed floating-point values with a tolerance, such as std::abs(a - b) < 1e-9, and remember that NaN compares unequal to everything, including itself. Floating-Point Numbers covers the right way to pick a tolerance.

Comparing strings

std::string supports all six operators. == compares the characters, and < compares lexicographically, like a dictionary, character by character using the character codes. So "apple" < "banana" is true, "Zebra" < "apple" is also true (uppercase codes are smaller), and "car" < "carpet" is true because a prefix comes first. You'll learn more in Strings with std::string.

There is one trap: two string literals like "abc" == "abc" are character arrays, so == compares their addresses, not their text. Make at least one side a std::string (or use std::string_view). C-Style Strings explains why.

No chained comparisons

In math you write 0 โ‰ค x โ‰ค 100. In C++, 0 <= x <= 100 compiles but means (0 <= x) <= 100: the first comparison produces true or false, which becomes 1 or 0, and that is always <= 100. So the whole expression is always true. GCC warns (comparisons like 'X<=Y<=Z' do not have their mathematical meaning). Write 0 <= x && x <= 100 instead.

The three-way comparison operator <=>

C++20 added <=>, which answers "less, equal or greater?" in a single operation. Its result isn't a bool but an ordering object from <compare> that you compare against 0:

C++
auto result = a <=> b;
if (result < 0)  { /* a is less than b */ }
if (result == 0) { /* a is equal to b */ }
if (result > 0)  { /* a is greater than b */ }

There are three ordering types, depending on what the values can express:

  • std::strong_ordering: equal values are truly interchangeable. Integers, characters, pointers and std::string give this.
  • std::weak_ordering: equivalent values may still be distinguishable, such as a case-insensitive comparison of "abc" and "ABC".
  • std::partial_ordering: some values can't be compared at all. Floating-point types give this, because NaN is neither less, equal nor greater than anything (the result is std::partial_ordering::unordered).

You rarely call <=> directly in everyday code. Its real power is in your own types: write one defaulted operator<=> and the compiler generates <, >, <= and >=, comparing the members in declaration order. A defaulted <=> also implicitly declares a defaulted ==, so you get == and != too.

C++ Comparing versions with a defaulted spaceship operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The defaulted operator compares major first, then minor, then patch, exactly like comparing version numbers by hand. Before C++20 you had to write all six operators yourself; you'll see the full story in Operator Overloading. (The doubled braces {{ in the format string print a literal {.)

Logical operators: &&, || and !

Logical operators combine bool values:

Operator Name True when
a && b logical AND both a and b are true
a || b logical OR at least one is true
!a logical NOT a is false

Their operands are converted to bool first: zero, a null pointer and false are false; everything else is true. The result is always a bool.

C++ Combining conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The two range checks illustrate De Morgan's laws, which tell you how to negate a combined condition:

  • !(a && b) is the same as !a || !b
  • !(a || b) is the same as !a && !b

So "not (at least 0 and at most 100)" becomes "less than 0 or greater than 100". Applying these laws often turns a confusing !( ... ) into a condition that reads naturally.

Short-circuit evaluation

&& and || evaluate their left operand first, and only evaluate the right one if it can still change the result:

  • In a && b, if a is false, the result is false and b is never evaluated.
  • In a || b, if a is true, the result is true and b is never evaluated.

This guarantee is what makes guard conditions safe. The left side checks that the right side is allowed to run:

C++
if (count != 0 && total / count > 50)       // no division by zero
if (ptr != nullptr && ptr->is_ready())      // no null dereference
if (i < v.size() && v[i] == target)         // no out-of-bounds read

Swap the operands in any of those lines and the program has undefined behavior whenever the guard fails.

C++ Watching short-circuiting happen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Short-circuiting also means a side effect on the right may simply never happen. In if (is_cached || load_from_disk()), the load runs only on a cache miss, which is usually what you want, but don't put work there that must always run.

The bitwise operators & and | also work on bool values but never short-circuit: both sides are always evaluated. Using & where you meant && turns a safe guard into a crash. Use && and || for conditions, and keep & and | for bit manipulation, covered in Bitwise Operators.

Precedence of comparison and logical operators

From tightest to loosest binding:

  1. ! (unary, binds tighter than everything below)
  2. arithmetic: * / %, then + -
  3. relational: < <= > >=, then <=> sits just above them
  4. equality: == !=
  5. &&
  6. ||

So a + 1 > b && c == d || e means ((a + 1 > b) && (c == d)) || e. Two consequences catch people out:

  • !x == 5 means (!x) == 5, which compares true or false (1 or 0) with 5, so it's always false. Write !(x == 5) or simply x != 5.
  • && binds tighter than ||, so is_admin || is_owner && is_active means is_admin || (is_owner && is_active). If you meant the other grouping, add parentheses. GCC warns about mixing them without parentheses (suggest parentheses around '&&' within '||'), and adding them is good style anyway.

The complete table lives in Operator Precedence.

Alternative tokens: and, or, not

C++ also accepts words for the logical operators. They are real keywords, so no header is needed:

Symbol Keyword
&& and
|| or
! not
!= not_eq

There are bitwise ones too (bitand, bitor, xor, compl, and compound forms like and_eq). if (logged_in and not banned) is perfectly valid C++ and some teams like how it reads. Most codebases stick to the symbols, though, so you need to recognize both but should follow your project's style. (MSVC only accepts the keywords in its conforming mode /permissive-, which is the default for new projects.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With int x = 150;, what is the value of 0 <= x <= 100?

    It means (0 <= x) <= 100. The first part is true (1), and 1 <= 100 is true. The expression is always true; write 0 <= x && x <= 100.
  2. 2. What happens in if (count != 0 && total / count > 50) when count is 0?

    && short-circuits: once the left side is false, the result must be false, so the division never runs.
  3. 3. Which declaration gives a struct all six comparison operators in C++20?

    A defaulted <=> generates <, >, <= and >=, and also implicitly declares a defaulted ==, from which != is derived.
  4. 4. With int t = -1; unsigned int lim = 10;, what is t < lim?

    The usual arithmetic conversions turn -1 into 4294967295 before comparing. Use std::cmp_less(t, lim) to compare the real values.
  5. 5. Which condition is equivalent to !(age >= 18 && has_id)?

    By De Morgan's law, not (A and B) is (not A) or (not B). The negation of age >= 18 is age < 18.

Summary

  • == != < > <= >= compare values and produce a bool; operands go through the usual arithmetic conversions first.
  • Comparing signed with unsigned converts negative values to huge ones; use std::cmp_less and friends (C++20) when types differ.
  • Don't compare computed floating-point values with ==, don't compare string literals with ==, and don't chain comparisons like a < b < c.
  • a <=> b (C++20) returns an ordering you compare with 0; defaulting it in a class gives you all six comparisons.
  • &&, || and ! combine conditions. && and || short-circuit, which makes guards like p && p->ok() safe.
  • ! binds tightest, then comparisons, then &&, then ||. Use parentheses when you mix && and ||.
  • and, or and not are valid keyword spellings of &&, || and !.

Next: Bitwise Operators, where you'll work with individual bits using & | ^ ~ << >>.