0

The usual concept of passing a variable by reference to a function is that you want to use that exact variable and not its copy, which is fine. But suppose you have this code:

#include <iostream>
using namespace std;

    int dev(int &a, int b)
    {
        a = 5 + b;
        return b;
    }
    int main()
    { 
        int a = 0;
        int b;
        cin >> a >> b;
        cout << dev(a, b) << " "<< a;
        return 0;           
    }

for inputs a = 5, b = 10 I am expecting to output 10 15, but I get 10 5.

Now the problem goes away if instead of

    cout << dev(a, b) << " "<< a;

I write

int res = dev(a,b);
cout << res << " " << a;

I was wondering why it would be so?

Edit: spelling

Vahagn Tumanyan
  • 412
  • 1
  • 7
  • 26
  • 3
    `cout << dev(a, b) << " " << a` is undefined behavior. The standard does not specify in what order the expressions `dev(a, b)` and `a` are evaluated. – Greg Kikola Feb 12 '17 at 20:23
  • Well, that makes sense. I'd expect to do it in exact order specified, hence the confusion. Please answer the question, so I can credit you properly. – Vahagn Tumanyan Feb 12 '17 at 20:24
  • Generally it makes sense not to mix computations and output anyway. – Bo Persson Feb 12 '17 at 20:30
  • @Bo Persson Alright, since this is marked as duplicate and _it is in fact_ a duplicate, should I remove it? – Vahagn Tumanyan Feb 12 '17 at 20:32
  • In general, avoid expressions having multiple subexpressions with side effects that affect the same variable. There are exceptions though where the order of evaluation is specified: the comma operator `,`, the ternary conditional operator `?:` and the logical operators `&&` and `||` are required to have their operands evaluated from left to right (with short-circuit evaluation on the latter two of course). All bets are off on other operations though. – Greg Kikola Feb 12 '17 at 20:33
  • @Vahagn - deleting is up to you. Generally, having more duplicates might help others find the answer. – Bo Persson Feb 12 '17 at 20:36

0 Answers0