Join Regular Classroom : Visit ClassroomTech

Unary Operator in C

What is Unary Operator in c ?

unary operators are used for produce a new value. This operator require only one operand.

Types of Unary operators:

  •  Unary minus(-)
  •  Increment (++)
  •  Decrement (–)
  •  NOT(!)
  •  Address operator(&)
  •  sizeof()

Unary Minus (-) :

It is a unary operator which is used for changing the sign of a variable.
A positive number turns into a negative number and a negative number turns into a positive.

Example :

int a = 10,b ;
b = -a ; // b is assigned with -10

Increment (++) :

An increment operator is used to increment a variable by 1. The increment can be done in two ways.

i. Pre Increment :

In this method, the value of the variable is increment before it is used
 General syntax: ++a ( a is an integer variable).

Example :

int a=2, b;
b = ++a ; // here b = 3  

ii. Post Increment (- -)

 In this method, the value of the variable is incremented after it is used.
 General syntax: a++ (a is an integer variable)

Example :

int a= 2, b, c ;
b = a++ ; // b = 2
c = a ; // c = 3

As this is a post increment so in the 2nd line the value of b remains 2 but then in the 3rd line c variable is stored by 3  incremented by 1.

Decrement (- -) :

Decrement Operator is a method to decrement a variable by 1. It can be done in two ways.

i. Pre Decrement :

In this method, the value of a variable is decrement before it is used.
General syntax: –a (a is an integer variable).

Example :

int a = 2, b ;
b = –a ; // Here b = 1

As it is pre decrement the value of a is decremented by 1 before store in the variable b.

ii. Post Decrement :

In this method, the value of a variable is decremented after it is used.
General syntax: a– (a is an integer variable).

Example :

int a= 2, b, c ;
b = a–;     // Here b = 2
c = a ;      // Here c = 1

As it is post decrement, in the 1st line the value of b remains 2. But in the 2nd line, the value is decremented by 1 and stored in the variable c.

NOT (!) :

It is used to reverse the state of an operand.

If x is false then !x is true
If x is true then !x is false.

Addressof Operator(&) :

It returns the address of a memory location of a variable.

Example:

int a;
int *ptr;
ptr = &a;      // here the address of integer variable a is copied at pointer variable ptr.

sizeof( ) :

It is a unary operator in c which is used to calculate the size of data types.

Example :

Recent Posts