Trusted answers to developer questions

What is a unary operator?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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)

RELATED TAGS

basics
unary
operator
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?