-2

I am decrementing an integer while passing it to a function. But am seeing some unexpected behavior. I'm new to C, and not sure what to make of it:

#include <stdio.h>

void func(int, int);

int main(){
        int i=3;
        //func(i--, i); //Prints a=3, b=2
        func(i, i--); //Prints a=2, b=3 ??
        func(i, --i); //Prints a=2, b=2 ??
}

void func(int a, int b){ 
        printf("a=%d\n", a); 
        printf("b=%d\n", b); 
}

The first call to func works as expected, but what is the deal with the second and third calls?

Plasty Grove
  • 2,807
  • 5
  • 31
  • 42

3 Answers3

1

This is undefined bahavior, you can't expect either result.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

The order of calculation of function arguments is not specified. E.g. GCC likes to calculate the argument values from right to left. When you have an operator that modifies a variable (or have any other side effect), there must be a sequence point between that operator and any other expression that uses that variable.

nullptr
  • 11,008
  • 1
  • 23
  • 18
-2

Since parameters passes in a function from right, so in first call where you used post increment operator- it passes the same value (3) and update the value for 'i' left parameter (2).

while in second call, you used pre increment operator which changes itself for right parameter and sends updated values for left parameter.

Prateek Shukla
  • 593
  • 2
  • 7
  • 27
  • Although this may be true for some compilers, the order of parameters' evaluation is not specified. – nullptr Jul 13 '13 at 06:45
  • This is as per turbo compiler. – Prateek Shukla Jul 13 '13 at 06:51
  • Well, I suppose you've given the most exact answer to the question: you have told why it's so for some given implementation of C. But the answer is rather narrow and even dangerous: one may think that evaluating parameters from right to left is always the case. In C standard, it's not specified. And writing programs that rely on some non-standardized behaviour of compiler is a great evil. Maybe this explains why your answer has been downvoted. – nullptr Jul 13 '13 at 07:07
  • @Inspired thanks for valuable information – Prateek Shukla Jul 13 '13 at 07:10