Incrementing or Decrementing a Variable in C Before or After You Use It - dummies

Incrementing or Decrementing a Variable in C Before or After You Use It

By Dan Gookin

The C language is full of shortcuts, and they’re wonderful things. First, they save you typing time. More importantly, the shortcuts let you express some ideas in quick yet fun and cryptic ways, which is okay; C programmers can still read your code — no problem.

The C shortcuts ++ and are used for incrementing (adding one to) and decrementing (subtracting one from), respectively. When you start assigning incremented or decremented values to other variables, though, you need to pay special attention to how you use ++ and .

Here’s a puzzle. If variable alpha equals 5, what’s the value of variable beta after this statement:

beta = alpha++;

The answer is 5. The reason is that the ++ is a post-incrementing operator. It increments the value of the variable after the variable is used. Here’s the code to prove it:

#include <stdio.h>
int main()
    int alpha,beta;
    beta = alpha++;
    printf("Alpha = %dn",alpha);
    printf("Beta = %dn",beta);

Type this code into your editor, save it, compile it, and run it:

Alpha = 6
Beta = 5

If you want to increment alpha before you assign its value to beta, remember that you can always split Line 8 in two:

beta = alpha;

Or, you can take advantage of the fact that the ++ operator can go on either side of the variable. When ++ appears before the variable name, as in ++alpha, it’s pre-incrementing the value of alpha.

Edit Line 8 of the code to read

beta = ++alpha;

Save to disk. Recompile and run. Observe the output:

Alpha = 6
Beta = 6

The value of alpha was incremented first, and then its value was assigned to variable beta.

You can do the same thing with the operator. If it appears after a variable, the variable is decremented after being used. Here’s how that modification looks on Line 8:

beta = alpha--;

Or, if the operator appears before the variable name, the value is decremented and then used:

beta = --alpha;

Note that this construction isn’t allowed:


This isn’t “double incrementing.” In fact, the compiler gets angry with you if you attempt such a thing.