James Balajan James Balajan - 1 month ago 5
C Question

Strange behaviour with decrement operator

My code is meant to print an array in reverse but for some reason the decrement operator isn't working as expected. According to my understanding

decrements the variable var before anything is done to it while
decrements the variable var after an operation has been complete such as a

Here is my code:

#include <iostream>

int main() {
int arrLen;
int arr[4];
scanf("%d\n %d %d %d %d", &arrLen, &arr[0], &arr[1], &arr[2], &arr[3]);
for (; arrLen >= 0; --arrLen)
printf("%d %d\n",arr[arrLen],arrLen);

return 0;

And here are my results (the right value in the output is the decremented variable, I added it to check):

0 4
2 3
3 2
4 1
1 0

Without the decremented variable being printed it should be:

0 2 3 4 1

Here are my expected results:

2 3 4 1


The reason this is not behaving as you expect is because of how for loops work.

for (statement_1; condition; statement_2) {

statement_1 is called only once before the loop begins.

condition is evaluated at the beginning of each pass in the loop. If it is true, body is evaluated. If not the loop exits.

statement_2 is evaluated after the body at the end of each pass in the loop, just before re-evaluating the condition.

So while --var does decrement and return the decremented value, it is only actually called after the body of your for loop each time it is run.

This means that --var and var-- will have the same effect on the behaviour of a for loop when part of statement_2.

To produce you desired behaviour you could change your for loop to this:

while (--arrLen >= 0)
    printf("%d %d\n", arr[arrLen], arrLen);