What is a unary operator?

Unary operators are those operators that require a single operand for computations.

Example

  • minus -
  • increment ++
  • decrement --
  • not ~

Minus

The minus operator is used to represent a negative value.

int a = -10 // Here `-` is used to represent a negative value

Increment

Prefix increment

The prefix increment operator precedes the operand and increments the value before using it, e.g., ++temp.

int a = 10;
// it increments `a` by one 
// value
// and assigns its value to `b`
int b = ++a;// b = 11
Postfix increment

The postfix increment operator follows the operand and increments the value after using it, e.g., temp++.

int a = 10;
// it assigns the value of `a` to `b`
// and then increments the value of `a` by one 
int b = a++;// b = 10
// a = 11

Decrement

Prefix decrement

The prefix decrement operator precedes the operand and decrements the value before using it, e.g., --temp.

int a = 10;
// it decrements `a` by one 
// value
// and assigns its value to `b`
int b = --a;// b = 9
Postfix decrement

The postfix decrement operator follows the operand and decrements the value after using it, e.g., temp--.

int a = 10;
// it assigns the value of `a` to `b`
// and then decrements the value of `a` by one 
int b = a--;// b = 10 
// a = 9

Not

The not operator is a bitwise operator that flips the bits of a value. The bits that are set will be unset and vice versa.

int a = 12; // (00001100)
int b = ~a; // (11110011)

Copyright ©2024 Educative, Inc. All rights reserved