The Wayback Machine - https://web.archive.org/web/20241001070614/https://www.geeksforgeeks.org/cpp-unary-operators/
Open In App

Unary Operators In C++

Last Updated : 12 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Unary operators in C++ are those operators that work on a single value (operand). They perform operations like changing a value’s sign, incrementing or decrementing it by one, or obtaining its address. Examples include ++ for increment, — for decrement, + for positive values, – for negative values,! for logical negation, and & for retrieving memory addresses. In this article, we will discuss various unary operators available in C++.

Types of Unary Operators in C++

C++ has a total of 8 unary operators which are as follows:

  1. Increment Operator (++)
  2. Decrement Operator (–)
  3. Unary Plus Operator (+)
  4. Unary Minus Operator (-)
  5. Logical NOT Operator (!)
  6. Bitwise NOT Operator (~)
  7. Addressof Operator (&)
  8. Indirection Operator (*)
  9. sizeof Operator

1. Increment Operator (++)

The increment operator is used to increase the value of its operand by 1. It works on the numeric operands and be use used as both prefix and postfix to the operand

Syntax

++ operand

or

operand ++

Example

C++




#include <iostream>
  
using namespace std;
  
int main()
{
    int x = 5;
  
    // Increment Operator (++)
    cout << "Initial value of x: " << x << endl;
    x++; // Increment x by 1
    cout << "After x++, x is now: " << x << endl;
  
    // Prefix and Postfix Increment/Decrement
    int a = 10;
    int b, c;
  
    b = ++a; // Prefix increment: first, increment a, then
             // assign to b
    c = a++; // Postfix increment: first, assign a to c,
             // then increment a
  
    cout << "a: " << a << ", b: " << b << ", c: " << c
         << endl;
  
    return 0;
}


Output

Initial value of x: 5
After x++, x is now: 6
a: 12, b: 11, c: 11

2. Decrement Operator (–)

The decrement operator is used to decrement the value by 1. Just like the increment operator, it can be used as pre-decrement and post-decrement. It works on numeric values.

Syntax

operand --

or

-- operand

Example

C++




// C++ program to illustrate the decrement operator
#include <iostream>
using namespace std;
  
int main()
{
  
    int var = 10;
    cout << "Value before decrement: " << var << endl;
    var--;
    cout << "Value after decrement: " << var;
    return 0;
}


Output

Value before decrement: 10
Value after decrement: 9

To know more about increment and decrement operators, refer to the article – C++ Increment and Decrement Operators

3. Unary Plus Operator (+)

The symbol (+) represents the unary plus operator in C++, which explicitly specifies the positive value of its operand. It doesn’t change the sign of a if it’s already positive, but it can be used for clarity in expressions.

– is the unary minus operator, which changes the sign of its operand to negative.

Explanation:

  • The unary minus (-) changes the sign of the value. If a is positive, -a makes it negative.
  • The unary plus (+) is used to explicitly specify a positive value. 

Syntax

+ operand

Example

C++




// C++ program to illustrate the unary plus operator
#include <iostream>
  
using namespace std;
  
int main()
{
    int a = 10;
    int c = +a; // Unary Plus: Explicitly specifies 'a' as
                // positive
  
    cout << "Original value of a: " << a << endl;
    cout << "After using unary plus (+a): " << c << endl;
  
    return 0;
}


Output

Original value of a: 10
After using unary plus (+a): 10

4. Unary Minus (-) Operator

The symbol (+) represents the unary plus operator in C++, which changes the sign of its operand to negative. If the operand is negative, this operator will make it positive and vice versa.

Syntax

- operand

Example

C++




// C++ program to illustrate the unary minus operator
#include <iostream>
using namespace std;
  
int main()
{
    int var = 20;
    cout << "Initial Value: " << var << endl;
    cout << "Value with (-): " << -var;
    
    return 0;
}


Output

Initial Value: 20
Value with (-): -20

5. Logical NOT Operator (!)

The logical NOT operator (!) is used for negating the value of a boolean expression. It returns true if the operand is false, and false if the operand is true.

Note: Zero is considered false and any non zero value is considered true in C++.

Syntax

! operand

Example

C++




// C++ program to illustrate the use of logical NOT operator
#include <iomanip>
#include <iostream>
using namespace std;
  
int main()
{
    bool isTrue = true;
    // Logical NOT: Negates the value of 'isTrue'
    bool isFalse = !isTrue;
  
    // print string correspoinding to true and false
    cout << boolalpha;
  
    cout << "Value of isTrue: " << isTrue << endl;
    cout << "Value of isFalse (!isTrue): " << isFalse
         << endl;
  
    return 0;
}


Output

Value of isTrue: true
Value of isFalse (!isTrue): false

6. Bitwise NOT Operator (~)

The bitwise NOT operator ~ in C++ performs a bitwise negation operation on integral data types, such as integers. It inverts each bit of the operand, changing every 0 bit to 1 and every 1 bit to 0′.

Syntax

~ operand

Example

C++




// C++ program to illustrate the use of first complement
// operator
#include <iostream>
  
using namespace std;
  
int main()
{
    // Binary: 0000 0101
    unsigned int a = 5;
    // Bitwise NOT: Inverts each bit of 'a'
    unsigned int b = ~a;
  
    cout << "Original value of a: " << a
         << " (Binary: 0000 0101)" << endl;
    cout << "Value of b after ~a: " << b
         << " (Binary: 1111 1010)" << endl;
  
    return 0;
}


Output

Original value of a: 5 (Binary: 0000 0101)
Value of b after ~a: 4294967290 (Binary: 1111 1010)

7. Addressof Operator (&)

The addressof operator (&) retrieves the memory address of a variable. It returns the memory location where the variable is stored in the computer’s memory.

Syntax

& operand

Example

C++




// C++ program to illustrate the use of addressof operator
#include <iostream>
  
using namespace std;
  
int main()
{
    int number = 42;
    // Pointer 'ptr' stores the address of 'number'
    int* ptr = &number;
  
    cout << "Value of number: " << number << endl;
    cout << "Address of number: " << &number; << endl;
  
    return 0;
}


Output

Value of number: 42
Address of number: 0x7fff5785a304

8. Dereference Operator (*)

The dereference operator (*) is used to access the value at a specific memory address stored in a pointer. It “points to” the value stored at that  Sddress.

Syntax

* operand

Example

C++




// C++ program to illustrate the dereferencing operator
#include <iostream>
using namespace std;
  
int main()
{
    int var = 10;
    int* ptr = &var;
  
    cout << "var = " << var << endl;
    cout << "*ptr = " << *ptr;
    return 0;
}


Output

var = 10
*ptr = 10

9. sizeof Operator

The sizeof operator is a special unary operator in C++ that returns the size of its operand it bytes. Its operand can be any data type or a variable.

Syntax

sizeof (operand)

Example

C++




// C++ program to illustrate the use of sizeof operator
#include <iostream>
using namespace std;
  
int main()
{
    // integer array with 10 elements
    int arr[10];
  
    // finding size of integer
    cout << "Integer Size: " << sizeof(int) << endl;
    cout << "Size of Integer Array with Elements: "
         << sizeof(arr);
    return 0;
}


Output

Integer Size: 4
Size of Integer Array with Elements: 40

Precedence and Associativity of Unary Operators in C++

Precedence of Unary Operators

Unary operators generally have a higher precedence than most binary operators. They have a fixed order of execution before most binary operations.

Associativity of Unary Operators

Unary operators are right-associative, meaning that if multiple unary operators are applied to the same operand, they are evaluated from right to left.

Example

  • int a = 5;: Initializes variable ‘a’ with the value 5.
  • int b = -++a;: In this expression:
  • ++a is a prefix increment, which increments the value of ‘a’ by 1.
  • – is the unary minus operator that changes the sign of the value obtained from ++a.
  • Then display the initial value of ‘a’ and the value of ‘b’ after applying the unary operators.

C++




// C++ program to illustrate the precedence and
// associativity of the unary operators
#include <iostream>
using namespace std;
  
int main()
{
    int a = 5;
  
    // Demonstration of unary operators' precedence and
    // associativity
    int b = -++a;
  
    cout << "Initial value of a: " << a << endl;
    cout << "Value of b (-++a): " << b << endl;
  
    return 0;
}


Output

Initial value of a: 6
Value of b (-++a): -6


Similar Reads

reinterpret_cast in C++ | Type Casting operators
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.It does not check if the pointer type and data pointed by the pointer is same or not. Syntax : data_type *var_name = reinterpret_cast <
3 min read
unordered_set operators in C++ STL
Unordered_set provides two operators in C++ STL. These are: Syntax: 1. (unordered_set &lhs == unordered_set &rhs) 2. (unordered_set &lhs != unordered_set &rhs) These operators are discussed in detail below: unordered_set == operator in C++ STL The ‘==’ is an operator in C++ STL performs equality comparison operation between two unor
5 min read
C++ Pointer Operators
Prerequisite: Pointers in C++ A pointer variable is a variable that stores the address of another variable or in other a pointer variable points to the variable whose address is stored inside it. Syntax: int *pointer_name; There are mainly two types of Pointer operators mainly used: Address of operator (&)The indirection operator/Dereference op
2 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction, ‘*’ is used for multiplication, etc. In simple terms, arithmetic operators are used to perform arithmetic operations on variables and data; they follow the same relationship betwe
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(>>/<<) Overloading in C++ We can't directly use the Input/Output Operators (>
2 min read
C++ Increment and Decrement Operators
Prerequisite: Operators in C++ What is a C++ increment Operator? The C++ increment operator is a unary operator. The symbol used to represent the increment operator is (++). The increment operator increases the value stored by the variable by 1. This operator is used for Numeric values only. There are two types of C++ increment Operator: Pre-Increm
4 min read
C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result. There are mainly 6 Comparison Operators namely: Greater than (>) : this operator checks whether operand1 is greater than operand2. If the result turns out to be true, it returns true or else retur
3 min read
C++ Relational Operators
In C++ programming language, we sometimes require to compare values and expressions. This comparison allows us to determine relationships, make decisions, and control the flow of our programs. The relational operators in C++ provide the means to compare values and evaluate conditions. In this article, we will learn about C++ relational operators an
4 min read
C++ Logical Operators
In C++ programming languages, logical operators are symbols that allow you to combine or modify conditions to make logical evaluations. They are used to perform logical operations on boolean values (true or false). In C++, there are three logical operators: Logical AND ( && ) OperatorLogical OR ( || ) OperatorLogical NOT ( ! ) OperatorLet's
4 min read
Assignment Operators In C++
In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other wor
7 min read
What are the Operators that Can be and Cannot be Overloaded in C++?
There are various ways to overload Operators in C++ by implementing any of the following types of functions: 1) Member Function 2) Non-Member Function 3) Friend Function List of operators that can be overloaded are: + - * ? % ? & | ~ ! = < > += -= *= ?= %= ?= &= |= << >> <<= >>= == != <= >= && ||
4 min read
Increment (Decrement) operators require L-value Expression
What will be the output of the following program? #include<stdio.h> int main() { int i = 10; printf("%d", ++(-i)); return 0; } A) 11 B) 10 C) -9 D) None Answer: D, None - Compilation Error. Explanation: In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Provi
1 min read
Order of operands for logical operators
The order of operands of logical operators &&, || are important in C/C++. In mathematics, logical AND, OR, etc... operations are commutative. The result will not change even if we swap RHS and LHS of the operator. In C/C++ (may be in other languages as well)  even though these operators are commutative, their order is critical. For example
1 min read
const_cast in C++ | Type Casting operators
C++ supports following 4 types of casting operators: 1. const_cast 2. static_cast 3. dynamic_cast 4. reinterpret_cast 1. const_cast const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class members inside a const member function. Consider th
4 min read
Overloading stream insertion (<>) operators in C++
In C++, stream insertion operator "<<" is used for output and extraction operator ">>" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be overloaded as a global function. And if we want to
2 min read
How to sum two integers without using arithmetic operators in C/C++?
Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...? Method 1 (Using pointers)An interesting way would be: C/C++ Code // May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum(int a, int b) { char *p = a; return (int)&amp;p[b]; } Despite
4 min read
Conditionally assign a value without using conditional and arithmetic operators
Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked: If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'. Note: - You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /)
6 min read
Written version of Logical operators in C++
Can we use keywords in place of operators in C++ ? Yes, certainly, we can. The ANSI C++ Standard has proposed keywords for several C++ operators . They originated in C in the header at the time when there were keyboards that couldn't type the required symbols like &&, !, || etc. In C++, they became alternate token just like regular tokens, except f
2 min read
Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. Parameters : Two Strings required t
2 min read
Casting Operators in C++
Casting operators are used for type casting in C++. They are used to convert one data type to another. C++ supports four types of casts: static_castdynamic_castconst_castreinterpret_cast1. static_castThe static_cast operator is the most commonly used casting operator in C++. It performs compile-time type conversion and is mainly used for explicit c
5 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications?  One use of dynamically allocated memory is to allocate memory
6 min read
Bitwise Operators in C++
There are various Operators present in C++. Every Operator has a particular symbol as well as an Operation to perform. We have various categories of operators in C++. Arithmetic OperatorsRelational OperatorsLogical OperatorsAssignment OperatorsBitwise OperatorsIn this article, we will learn about the Bitwise Operators in C++. C++ Bitwise OperatorsB
6 min read
Operators in C++
An operator is a symbol that operates on a value to perform specific mathematical or logical computations. They form the foundation of any programming language. In C++, we have built-in operators to provide the required functionality. An operator operates the operands. For example,  int c = a + b;Here, '+' is the addition operator. 'a' and 'b' are
13 min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Conversion Operators in C++
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading function in class. In this article, we will learn
4 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Practice Tags :