C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

Prefix and postfix operators produce identical results when used by themselves. Only when you
combine them with other expressions does a small “gotcha” appears. Consider the following code:


int i = 2, j = 5, n;
n = ++i * j;

The question is, what is n when the statements finish executing? It’s easy to see what’s in j because j
doesn’t change and still holds 5. The ++ ensures that i is always incremented, so you know that i
becomes 3. The trick is determining exactly when i increments. If i increments before the
multiplication, n becomes 15, but if i increments after the multiplication, n becomes 10.


The answer lies in the prefix and postfix placements. If the ++ or -- is a prefix, C computes it before
anything else on the line. If the ++ or -- is a postfix, C computes it after everything else on the line
finishes. Because the ++ in the preceding code is a prefix, i increments to 3 before being multiplied
by j. The following statement increments i after multiplying i by j and storing the answer in n:


Click here to view code image


n = i++ * j; /* Puts 10 in n and 3 in i */

Being able to increment a variable in the same expression as you use the variable means less work on
the programmer’s part. The preceding statement replaces the following two statements that you would
have to write in other programming languages:


n = i * j;
i = i + 1

Note

The ++ and -- operators are extremely efficient. If you care about such things (most of
us don’t), ++ and -- compile into only one machine language statement, whereas
adding or subtracting 1 using +1 or -1 doesn’t always compile so efficiently.

Let’s revisit the count up and count down program from Chapter 10, this time using the prefix
increment and decrement operators. This involves even fewer lines of code than the last program; we
can even cut the code to fewer lines when you learn about loops in the next chapter.


Click here to view code image


// Example program #2 from Chapter 13 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter13ex2.c
/* This program increases a counter from 1 to 5, printing updates
and then counts it back down to 1. However, it uses the increment
and decrement operators */
#include <stdio.h>
main()
{
Free download pdf