Unary Operators

Unary operators are operators that take exactly one argument.

Unary Arithmetic Operators

Unary operators ++ and -- are the only operators in C which can be either prefix (e.g. ++k, --k) or postfix (e.g. k++, k--).

When used as prefix, operators ++ and -- (preincrement and predecrement) add or subtract one from the value of the operand before the evaluation. When used as suffix, operators ++ and -- (postincrement and postdecrement) add or subtract one from the value of the operand after the evaluation.

Operator Operation Precedence
+ unary plus does not affect the operand 14
- unary minus changes the sign of the operand 14
++ increment adds one to the value of the operand. Postincrement adds one to the value of the operand after it evaluates; while preincrement adds one before it evaluates 14
-- decrement subtracts one from the value of the operand. Postdecrement subtracts one from the value of the operand after it evaluates; while predecrement subtracts one before it evaluates 14

For example:

 int j = 5;
 k = ++j;          /* k = k + 1, j = k, which gives us j = 6, k = 6 */

but:

 int j = 5;
 k = j++;          /* j = k, k = k + 1, which gives us j = 5, k = 6 */

Unary Logical Operator

The ! (logical negation) operator produces the value 0 if its operand is true (nonzero) and the value 1 if its operand is false (0).

Operator Operation Precedence
! logical negation 14

The following two expressions are equivalent:

    !right;
right == 0;

Unary Bitwise Operator

The result of the ~ (bitwise negation) operator is the bitwise complement of the operand. In the binary representation of the result, every bit has the opposite value of the same bit in the binary representation of the operand.

Operator Operation Precedence
~ bitwise complement (unary); inverts each bit 14

Address and Indirection Operator

In the mikroC PRO for PIC, address of an object in memory can be obtained by means of an unary operator &. To reach the pointed object, we use an indirection operator (*) on a pointer. See Pointers section for more details.

Operator Operation Precedence
* accesses a value indirectly, through a pointer; result is the value at the address to which operand points 14
& gives the address of its operand 14
Example:
 int *p_to_y;    // p_to_y is defined as a pointer to an int
 int y;          // y is defined as an int
	
 p_to_y = &y;    // assigns the address of the variable y to the pointer p_to_y
 *p_to_y = 3;    // causes the variable y to receive the value 3

  Note : Besides these, sizeof and casting unary operators are supported also.
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code