Ad Code

Unary Operators in C Languages

Unary Operators include

  • Increment (++) and Decrement (--) Operators
  • Minus (-) Operator
  • Address (&) and Size SizeOf Operators

These operators are Unary Operators because they act on only one operand.
Unary Operators will be given the highest priority over binary and ternary operators. While evaluating expressions unary operators follow right to left associativity.

Operator Description (or) Action
++ Increment Operator
-- Decrement Operator
- Minus Operator
& Address Operator
SizeOf Sizeof Operator

Increment (++) and Decrement (--) Operators :

The operator ++ adds one to its operand, wheras the operator -- subtracts one from its operand.

x = x + 1; can be written as x++
x = x - 1; can be written as x--

if ++ and -- are used as suffix to the variable name, then the post increment of decrement operations take place.

If ++ and -- are used as prefix to the variable name, then pre increment/decrement operations take place.

Example : 1
x = 20;
y = 10;
z = x * y++;

Here, the current value of y is used for product and after performing the operation, the value of y is incremented.

Result is, z = 20 * 10 = 200;

Example : 2
x = 20;
y = 10;
z = x * ++y;

Here, the value of y is incremented first and then used for the product.

Result is, z = 20 * 11 = 220

Minus (-) Operator

Minus Operator is used to indicate or change the algebraic sign of a value.

Example : 1
int x = -50;
int y = -x;

First assignment, assigns the value -50 to x and the second assignment assigns the value of 50 to y through x.
The - sign used in this way is called unary oerpator, because it takes only one operand.

Address (&) and Size SizeOf Operators

The sizeof operator gives the bytes occupied by a variable. The number of bytes occupied varies from variable to variable.

The & (address) operator prints the address of the variable in the memory.

Program : This program explains the Sizeof and Address Operators

    int x = 2;
    float y = 2;
    printf("sizeof(x)=%d bytes \n", sizeof(x));
    printf("sizeof(y)=%d bytes \n", sizeof(y));
    printf("address of x=%u and y = %u", &x, &y);
Output :
sizeof (x) = 2 bytes
sizeof (y) = 4 bytes
Address of x = 4066 and y = 25096

Post a comment