How to Allocate Space for a Structure in C Programming
How to Create Endless Loops in C Programming
How to Free Memory in C Programming

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

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;
    alpha=5;
    beta = alpha++;
    printf("Alpha = %d\n",alpha);
    printf("Beta = %d\n",beta);
    return(0);
}

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:

alpha++;
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:

++alpha++;

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

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Share Variables between Modules When Programming in C
How to Work with Character Variables in C Programming
C Programming: How to Work Pointer Math in an Array
How to Use Specific Variable Types in C
How to Use the if Function in C Programming
Advertisement

Inside Dummies.com