Thursday 21 August 2014

Unary operators

Unary operator:- which works upon a single operand.
                                                Example:  unary minus, increment, decrement operators.

Unary minus(-) :-
int a, b=5;
a=-(a);
then the result : a= -5,

increment(++) and decrement(--) operator :-
let   int a=5;
++a;   // is equivalent to a=a+1;
--a;   // is equivalent to a=a-1;
Increment / decrement operators have two variant :
11)      Prefix (++a)
22)      Postfix(a++)

Both add +1 to the variable a, but note the difference in the example given below:
                int a=5,b;

                b = a++;
is equivalent to writing:
                b = a;
                a=a+1;
whereas,
                b = ++a;
is equivalent to writing:
                a=a+1;
                b=a;

so conclusion for above example:  postfix(b=a++;)    the value of b=5.

                                                                    Prefix( b=++a;)  the value of b=6.

No comments:

Post a Comment