Unary Operator

What is a Unary Operator?

Unary Operators are the operators which require only one operand. While binary operator requires two operands and tertiary requires three operands.

Unary operators are:
+, -, ++, --, sizeof()


1) + and -

 Note: (+) and (-) are not of addition and subtraction but it denotes only sign of operator as positive or negative.

Ex.
+1, +2, +3...
-1, -2, -3...


2) ++ and --


It seems to be  ++ (two plus-plus), But it is a single operator.
It is called the increment operator.

Increment operator are of two type:

  • i) Pre increment
  • ii) Post increment


The meaning of both the increments is the same.

i.e To add +1 in  any value x++ or ++x;
or to increase the value by 1.
x++ is x=x+1

where x is a variable.

Example:
7++ output is 8
25++ output is 26

program: (Pre-increment) 

#include <stdio.h>
#include <conio.h>
int main()
{
    int x=7;
    ++x;  //Where  x++ or ++x increase the value by 1.
    printf("Pre-increment is %d", x);
    getch();
    return 0;
}

Output:
8

Note: Here it is giving output by adding one before 7 (1+7=8).

program: (Post-increment) 

#include <stdio.h>
#include <conio.h>
int main()
{
    int x=7;
    x++;  //increase the value by 1.
    printf("Post-increment is %d", x);
    getch();
    return 0;
}

Output:
8

Note: Here it is giving output by adding 1 after 7 (7+1=8).




What is the difference between post-increment and pre-increment?

The operator is written after the variable. The operator is written before the variable.
The priority of the post-increment is the least even more than assignment operators (An exceptional rule). While the priority of pre-increment is the most.



3) Decrement Operator
The decrement operator is also the same as an increment operator. But it decreases the value by 1.

Decrement operators are of two types:
i) Pre decrement
ii) Post decrement

The meaning of both the decrements operators is the same.

i.e To substract -1 in  any value x-- or --x;
or to decrease the value by 1.
x-- is x=x-1

where x is a variable.

Example:
7-- output is 6
25-- output is 24

program: (Pre-decrement) 

#include <stdio.h>
#include <conio.h>
int main()
{
    int x=7;
    --x;  //Where  x-- or --x deccrease the value by 1.
    printf("Pre-increment is %d", x);
    getch();
    return 0;
}

Output:


6


Note: Here it is giving output by subtracting one (7-1=6).

program: (Post-decrement) 

#include <stdio.h>
#include <conio.h>
int main()
{
    int x=7;
    x--;  //decrease the value by 1.
    printf("Post-decrement is %d", x);
    getch();
    return 0;
}

Output:




6

Comments

Popular posts from this blog

Getting input in C