0

I have a function that takes one argument by address and changes the value of the argument. But when I call the function, the order of execution is different in cases of addition and subtraction:

#include <iostream>
using namespace std;

int fun(int *i) {
    *i += 5;
    return 4;
}

int main()
{
    int x = 3;
    x = x + fun(&x);
    cout << "x: " << x << endl;
    
    int y = 3;
    y = y - fun(&y);
    cout << "y: " << y << endl;

    return 0;
}

The output of the above code is:

x: 12

y: -1

which means x is first changed in the function and then added to itself (I expected x to become 7), but the changes on y don't affect the y before subtraction operator.

Why is this happening?

Hadi GhahremanNezhad
  • 2,377
  • 5
  • 29
  • 58
  • 1
    Is it defined behavior? If not, anything goes and you can't complain. – President James K. Polk Dec 07 '21 at 19:46
  • 2
    The evaluation order of operator and function arguments is unspecified. `fun(&x)` may be evaluated before `x` and vise versa. https://stackoverflow.com/questions/33598938/order-of-evaluation-of-assignment-statement-in-c – 273K Dec 07 '21 at 19:50
  • 1
    Looks like this is [entry #2](https://en.cppreference.com/w/cpp/language/eval_order#Undefined_behavior) in the "undefined behavior" section here. – Nathan Pierson Dec 07 '21 at 19:51
  • 1
    @S.M. And because `fun(&x)` has a side effect on `x`, the resulting code is actually UB not merely unspecified. – Nathan Pierson Dec 07 '21 at 19:51
  • @S.M. does it mean the output can change at different runs? Because currently, the output is (12, -1) every time I run it. – Hadi GhahremanNezhad Dec 07 '21 at 19:54
  • @PresidentJamesK.Polk does it mean the output can be different if I run it again? – Hadi GhahremanNezhad Dec 07 '21 at 19:57
  • 1
    It means you don't know what could happen to the output for each run. – edtheprogrammerguy Dec 07 '21 at 19:59
  • 2
    Yes, it means it can be different on different runs. I wouldn't expect it to be, but I'd consider any program with undefined behavior to be a buggy and in need of repair. – President James K. Polk Dec 07 '21 at 19:59
  • 1
    @HadiGhahremanNezhad -- You're concerned about different runs -- how about with different compiler options, compiler versions of the same compiler, or different compiler brands altogether? You write code like this for version x of the compiler, you upgrade to version y, and then all of a sudden, your program is broken. – PaulMcKenzie Dec 07 '21 at 20:04
  • @PaulMcKenzie thanks. I tested this with different compilers and different versions of C++ and every time the output was the same. I thought there might be a rule for the `+` and `-` operators, but now I know it is undefined behavior. – Hadi GhahremanNezhad Dec 07 '21 at 20:08

0 Answers0