-2

I cannot figure out the reason why I am getting this result. I am not the order in which the function calls it's arguments. I would assume that it would start at the first argument and go until the last. Here's the code...

#include <stdio.h>

int addmeup(int a, int b, int c){

    printf("a:%d\n", a);
    printf("b:%d\n", b);
    printf("c:%d\n", c);

    return a + 2 * b + 3 * c;

}
int main(){

    int x = 1;
    int y = addmeup(x++,x++,x++);

    printf("x:%d\n", x);
    printf("y:%d\n", y);

    return 0;
}

I don't know why the result I am getting is...

a:3
b:2
c:1
x:4
y:10

For the function addmeup() why wouldn't the a be 1 instead of 3? Then b would be 2 and c would be 3. But it is the opposite. Can't seem to wrap my head around this.

Tony
  • 35
  • 5

2 Answers2

1

In C and C++ the evaluation order of function arguments is undefined. It could be left to right, right to left, or randomized by running on multiple threads.

Also your example is even worse than that because function(x++, x++, x++) modifies x multiple times without a sequence point. Function argument commas are not sequence points. Which means x might be sent into the function call as x, x+1, x+2 or x+3. Since it is undefined it could even be 0 or call abort().

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
0

It is a undefined behaviour. It means anything can happen.

See GCC warning:

prog.c: In function 'main':
prog.c:15:30: warning: operation on 'x' may be undefined [-Wsequence-point]
   15 |     int y = addmeup(x++,x++,x++);
      |                             ~^~
prog.c:15:30: warning: operation on 'x' may be undefined [-Wsequence-point]
msc
  • 33,420
  • 29
  • 119
  • 214