Node:Postfix and prefix ++ and --, Next:Arrays and hidden operators, Previous:Hidden assignments, Up:Hidden operators and values
Postfix and prefix ++
and --
Increment (++
) and decrement (--
) expressions also have
values, and like assignment expressions, can be hidden away in
inconspicuous places. These two operators are slightly more complicated
than assignments because they exist in two forms, postfix (for example,
my_var++
) and prefix (for example, ++my_var
).
Postfix and prefix forms have subtly different meanings. Take the
following example:
int my_int = 3; printf ("%d\n", my_int++);
The increment operator is hidden in the parameter list of the
printf
call. The variable my_int
has a value before the
++
operator acts on it (3) and afterwards (4).
Which value is passed to printf
? Is my_int
incremented
before or after the printf
call? This is where the two forms of
the operator (postfix and prefix) come into play.
If the increment or decrement operator is used as a prefix, the operation is performed before the function call. If the operator is used as a postfix, the operation is performed after the function call.
In the example above, then, the value passed to printf
is 3, and when
the printf
function returns, the value of my_int
is incremented
to 4. The alternative is to write
int my_int = 3; printf ("%d\n", ++my_int);
in which case the value 4 is passed to printf
.
The same remarks apply to the decrement operator as to the increment operator.