Unary Operators

Which Logical Operator Is a Unary Operator?

The only logical operator in C++ that is unary is the logical NOT, !. Learn why && and || need two operands, with a short example and a quick comparison.

On this page
  1. The answer is the logical NOT
  2. Why ! takes one operand
  3. Why && and || are binary
  4. Example program
  5. Telling the logical operators apart
  6. Logical NOT with comparisons
  7. A note on wording

The answer is the logical NOT

Of the three logical operators in C++, only the logical NOT (!) is a unary operator. Logical AND (&&) and logical OR (||) each need two operands, as in a && b and a || b.

If you are still getting used to unary operators in C++, the logical operators make a good first example, because only one of them takes a single operand.

Why ! takes one operand

The ! operator takes one operand and flips its truth value. !true is false, and !false is true. Numbers follow the same rule: zero counts as false, and any other value counts as true. So !0 is true, and !5 is false.

Why && and || are binary

&& gives true only when both operands are true. || gives true when at least one operand is true. Each one combines two conditions, so each is a binary operator.

Example program

This program prints the result of each expression:

#include <iostream>

int main() {
    bool ready = false;
    int count = 3;

    std::cout << std::boolalpha;
    std::cout << !ready << '\n';                // true, since ready is false
    std::cout << !count << '\n';                // false, since count is not zero
    std::cout << (count > 0 && !ready) << '\n'; // true
}

The program prints true, false and true, one per line.

Telling the logical operators apart

  • ! (logical NOT) takes one operand, so it is unary.
  • && (logical AND) takes two operands, so it is binary.
  • || (logical OR) takes two operands, so it is binary.

Logical NOT with comparisons

! is often paired with the c comparison operators, such as > and ==. Those produce a bool, and ! flips the result. For example, !(count > 0) is true only when count is zero or negative.

A note on wording

Write “a unary operator”, not “an unary operator”. “Unary” starts with a “y” sound, so “a” is the correct article.

The complete guide to unary operators

Unary Operators in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Shift Operators in C++

Learn how the << and >> shift operators work in C++, with binary examples, compound forms, precedence traps, undefined cases, and safe ways to use them.

C++ While Loop Syntax

Learn the C++ while loop syntax, how the condition is checked, and how to avoid infinite loops, with step-by-step examples you can compile and run.

While Loops 4 min read