Arithmetic Operators

Arithmetic operators are used to perform mathematical computations. They have numerical operands and return numerical results. The type char technically represents small integers, so the char variables can be used as operands in arithmetic operations.

All arithmetic operators associate from left to right.

Arithmetic Operators Overview

Operator Operation Precedence
Binary Operators
+ addition 12
- subtraction 12
* multiplication 13
/ division 13
% modulus operator returns the remainder of integer division (cannot be used with floating points) 13
Unary Operators
+ 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
  Note : Operator * is context sensitive and can also represent the pointer reference operator.

Binary Arithmetic Operators

Division of two integers returns an integer, while remainder is simply truncated:

/* for example: */
7 / 4;          /* equals 1 */
7 * 3 / 4;      /* equals 5 */

/* but: */
7. * 3. / 4.;   /* equals 5.25 because we are working with floats */

Remainder operand % works only with integers; the sign of result is equal to the sign of the first operand:

/* for example: */
9 % 3;          /* equals 0 */
7 % 3;          /* equals 1 */
-7 % 3;         /* equals -1 */

Arithmetic operators can be used for manipulating characters:

'A' + 32;          /* equals 'a' (ASCII only) */
'G' - 'A' + 'a';   /* equals 'g' (both ASCII and EBCDIC) */

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.

For example:

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

but:

int j = 5;
j = k++;          /* j = k, k = k + 1, which gives us j = 5, k = 6 */
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