Unary Operators

What Are Unary and Ternary Operators?

Learn the difference between unary and ternary operators in C++. A unary operator takes one operand and a ternary operator takes three, as in ?:.

On this page
  1. What a unary operator is
  2. What a ternary operator is
  3. Unary, binary and ternary side by side
  4. The same symbol can be unary or binary
  5. A short example
  6. Summary

What a unary operator is

A unary operator acts on one operand. Examples in C++ include the minus in -n, the logical NOT in !ready, and the increment in ++count. Each one needs only a single value, so there is nothing on the other side to combine it with.

What a ternary operator is

A ternary operator takes three operands. C++ has exactly one ternary operator, the conditional operator ?:. It is written as condition ? value_if_true : value_if_false. It checks the condition and then returns one of the two values, depending on whether the condition is true.

Here is a common use. The line below stores the larger of a and b in larger:

int larger = (a > b) ? a : b;

If a is greater than b, larger gets a. Otherwise, it gets b.

Unary, binary and ternary side by side

The kind of operator depends on how many operands it takes:

Kind Operands Examples
Unary 1 -n, !ready, ++count
Binary 2 a + b, a && b, a == b
Ternary 3 condition ? a : b

The same symbol can be unary or binary

The minus sign can be unary or binary. In -7, it negates the number, so it is unary. In 10 - 7, it subtracts, so it is binary. The plus sign works the same way, as in +7 and 10 + 7.

A short example

This program uses all three kinds:

#include <iostream>

int main() {
    int a = 7;
    int b = 3;

    int negative = -a;             // unary minus: one operand
    int sum = a + b;               // binary plus: two operands
    int larger = (a > b) ? a : b;  // ternary: three operands

    std::cout << negative << ' ' << sum << ' ' << larger << '\n';
}

The program prints -7 10 7.

Summary

Count the operands. One operand makes an operator unary, two make it binary, and three make it ternary. In C++, the ternary operator is ?:. The unary operators in C++ go beyond - and !, too, and include the increment and address-of operators.

The complete guide to unary operators

Unary Operators in C++
Read the guide

Keep exploring

Guides from other topics

All topics →