top of page

FE1008/CY1402-Pre and Post Increment/Decrement Operators

In this section, we will discuss more about increment and decrement operators which are operators to add 1 or minus 1 to the value of a variable. There are a total of 4 different operators, 2 for increment and 2 for decrement. For increment/decrement, they each have a pre- and a post- increment/decrement form respectively. This pre- and post- operators differ only in the order of increment and return of value. Pre-increment increments the value before returning the new value while post-increment returns the value before incrementing the value. The same is true for decrement operation.

Figure 1: Summary of Pre- and Post- Increment/Decrement Operators

Example

Consider the following code:

int main(void)

{

int w = 3, x = 3, y = 3, z = 3;

printf("%d\n", ++w); // line 4

printf("%d\n", x++); // line 5

printf("%d\n", --y); // line 6

printf("%d\n", z--); // line 7

printf("Final values are: w = %d, x = %d, y = %d, z = %d\n", w, x, y, z);

return 0;

}

What will be the expected output? and the final values of each variable?

For w

++w refers to pre-increment operation for variable w. Therefore, in line 4, ++w will return a value of 4 and it will be the first output. Variable w now holds a value of 4 and will display 4 in the final printf statement as well.

For x

x++ refers to post-increment operation for variable x. Therefore, in line 5, x++ will return the original x value of 3 to printf before incrementing it to 4. Line 5 will output 3 while variable x from that statement onwards will contain a value of 4. Hence, the final printf statement will output a value of 4 for x.

For y

--y refers to pre-decrement operation for variable y. Therefore, in line 6, --y will return the newly decremented value for y which is 2 into printf. From here on, y holds a value of 2 and the final printf will output a value of 2 for y.

For z

z-- refers to post-decrement operation for variable z. Therefore, in line 7, z-- will return the original value of z to printf while z will hold the decremented value of 2 from that statement onwards. The final printf statement will output a value of 2 for z.

Output:

4

3

2

3

Final values are: w = 4, x = 4, y = 2, z = 2

More in depth discussion

Operators are in fact functions and basic arithmetic operators such as +, -, *=, ++, etc... have their corresponding functions already defined in the C language. Just like the functions that you define (e.g. int main(void)), we have the option to return a value to the calling function/placeholder. And that is why I wrote "return" before increment or increment before "returning".

That's all for the topic on Pre and Post Increment/Decrement Operators. If you have any doubts, opinions or suggestions, feel free to leave them in forum section or email me @ KYX@outlook.sg. Thanks~

Recent Posts

Related Posts

Leave your comments or questions below:

bottom of page