C - Operator Increment Operator


Assuming the variables are of type int, the following three statements all have exactly the same effect:

count = count + 1;
count += 1;

Each statement increments count by 1.

The action of this operator is to increment the value of the variable, and the incremented value is used in the evaluation of the expression.

For example, suppose count has the value 5 and you execute this statement:

total = ++count + 6;

The variable count will be incremented to 6, and this value will be used in the evaluation of the expression on the right of the assignment.

total will be assigned the value 12, so the one statement modifies two variables, count and total.

Prefix and Postfix Forms of the Increment Operator

You've written the operator ++ in front of the variable.

This is called the prefix form of the operator.

You can write the operator after the variable, and this is referred to as the postfix form.

For count++, the incrementing of count occurs after its value has been used.

Consider the following code

total = 6 + count++;

With the same initial value of 5 for count, total is assigned the value 11.

This is because the initial value of count is used to evaluate the expression on the right of the assignment (6 + 5).

The variable count is incremented by 1 after its value has been used in the expression.

The preceding statement is therefore equivalent to these two statements:

total = 6 + count;

Related Topic