Search code examples
cfunction-callpre-increment

Is using pre-increment in a function call in C wrong?


void reverse(char *s,int j,int i) {
      printf("%d\t%d\n",i,j);
      if(i<j) {
        swap(s, i, j);
        reverse(s,--j,++i);
      }
    }

I read on Stack Overflow that using the postincrement operators in the function call can pose problems but does the use of the preincrement in function calls is also wrong??

Please help.


Solution

  • Increment operators cause undefined behavior if they modify the same variable in the same sequence point (statement). For example if you call a function like this: foo(++i, ++i) the C standard doesn't say in which order the increments should be performed, and you can't predict what will be passed to the function.

    This is not the case here, so your program's semantics are well defined. That is, i and j are incremented and then their values are passed to the function.