0

An unexpected behavior was observed when using the postfix addition operator in a printf statement. The code is similar as the one below:

#include <stdio.h>
    
int main()
{
    int array[4] = { 100, 200, 300, 400 };
    int i;
    int index = 0;
    
    for (i=0; i<4; i++) {
        printf("array[%d]: %d\n", index, array[index++]);
    }
}

Result:

array[1]: 100
array[2]: 200
array[3]: 300
array[4]: 400

In the printf statement, index was incremented by 1 before its value was printed on the terminal. I had originally assumed that the former index value would be printed first and then array[index], followed by incrementing the value of index.

To understand such a behavior, I proposed to think of the postfix operator as the following function:

int postfix_add(int *p) {
    int old_value = *p;
    *p = *p + 1;
    return old_value;
}

Then, the printf statement can be expressed as:

printf("array[%d]: %d\n", index, array[postfix_add(&index)]);

This would indeed explain the result as any function in a function argument should be evaluated first.

But my question is, does C really treat the postfix operator as such?

  • 2
    Best bet is to just do one thing at a time – Ed Heal Mar 10 '21 at 00:08
  • 1
    The fact that a function call in an argument would be evaluated before the enclosing function call does not imply it would be evaluated before other arguments. The C standard does not impose any order on the evaluation of arguments. (Why is this not taught correctly? Every C teacher ought to know to make clear that the order of function argument evaluation, and a number of other things, is not determined.) – Eric Postpischil Mar 10 '21 at 00:40
  • @EricPostpischil I don't think this is even taught *at all*. I've got several teachers/professors trying to teach me C through my entire education, none of them ever mentioned undefined behavior. Meh. – Marco Bonelli Mar 10 '21 at 01:47

0 Answers0