Increment and decrement.
The traditional method of incrementing numbers is by coding something like:
a =index.html 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....
- Prefix notation will increment the variable BEFORE the
expression is evaluated.
- 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.
Martin Leslie
27-Feb-95