Increment and decrement.


The traditional method of incrementing numbers is by coding something like:
	a = a + 1;

Within C, this syntax is valid but you can also use the ++ operator to perform the same function.

	a++;

will also add 1 to the value of a. By using a simular syntax you can also decrement a variable as shown below.

	a--;

These operators can be placed as a prefix or post fix as below:

	a++;		++a;

When used on their own (as above) the prefix and postfix have the same effect BUT within an expression there is a subtle difference....

  1. Prefix notation will increment the variable BEFORE the expression is evaluated.
  2. Postfix notation will increment AFTER the expression evaluation.

Here is an example:

	main()				main()
	{				{
	  int a=1;			  int a=1;
	  printf(" a is %d", ++a);	  printf(" a is %d", a++);
        }				}

In both examples, the final value of a will be 2. BUT the first example will print 2 and the second will print 1.


Example program.
Other operators.
Operator precedence table.

Top Master Index Keywords Functions


Martin Leslie