C++ Unary Operators

Advertisements
Advertisements

The unary operators take a single argument in C++ language. Some of the operators you have already seen in previous articles are unary operators.

Here is the list of unary operators.

Unary OperatorsDescription
*Dereference operator
&Address Of operator
Minus sign
!Not  operator
~Complement
++Increment operator
Decrement operator
typeForced type conversion
sizeofSize of the data type

Dereference Operator (*)

When a C++ pointer type is declared and it is pointing to a variable. The dereference operator helps to access the content of a pointer type.

We will learn more about while discussing pointers.

Address Of Operator(&)

It resembles the bitwise AND, but when used as a unary operator it returns the address of the variable.

Advertisements
int A = &B;

The variable A will store address of the variable B, not its value.

Minus Sign(-)

Minus is an arithmetic operator, but as a unary operator, it is used to denote a negative value. It is most commonly used the unary operator in C++ programs.

Negation Operator(!)

The negation is a logical operator which negates the value of a boolean variable. If the value is 1 (true) then, it becomes 0 (false). If the value is 0 (false) then, it becomes 1 (true).

Bitwise Complement (~)

The bitwise complement modifies the binary value of a variable to 2‘s complement binary value. In other words, you get a negative value for a positive number plus 1.

\begin{aligned}p = 45  \hspace{3px} becomes \hspace{3px} -46 \hspace{3px} after \hspace{3px} \sim p.\end{aligned}

Increment Operator (++)

The increment operator is used in loop structures. You will learn about loop structures later in this C++ tutorial. The increment operator increment an associated variable by 1.

i = 12;
i++; // same as saying i = i + 1;

The value of i after increment is 13.

Decrement Operator (–)

The decrement operator decreases the associated variable value by 1.

i = 34;
i--;

The value will be 33 after decrement.

Type Operator

The type conversion operator is used to modify the data type of a variable by force. The initial data type is changed to what specified in the type operator. It is also known as cast operator.

int A;
A = 10;
(float) A;

This will change the variable A into floating type from an integer.

Advertisements

Sizeof Operator( sizeof)

The sizeof operator is a special operator that returns the size of the data type in C++ program.

int A;
sizeof(A);

This will return the size of integer data type which is 4 bytes.

Bestseller

Let Us C++

One of the best selling book in C++ programming language. A perfect book for beginners and people who want to prefer self-study in step by step manner. Simple and easy narration style made this book very popular. The book assumes that you don’t have programming experience and starts with basic to more advanced topics.

Advertisements
Advertisements
Advertisements