Two different outputs for the same reference in "return by reference" function in C++

Viewed 43
#include <iostream>
using namespace std;
int& doSum(int a, int b){
    int sum = a + b;
    
    int &z = sum;
    return z;
}

int main() {
    int a1 = 2, a2=3;
    int &x = doSum(a1,a2);
    cout<<x<<endl;
    cout<<x<<endl;
    return 0;
}

OUTPUT: 5 21989

Why is the output showing two different values of "x" while no changes are made to "x" between the two "cout"s?

I tried using printf instead of cout and it works perfectly fine. Why is it so?

#include <iostream>
using namespace std;
int& doSum(int a, int b){
    int sum = a + b;
    
    int &z = sum;
    return z;
}

int main() {
    int a1 = 2, a2=3;
    int &x = doSum(a1,a2);
    printf("%d",x);
    printf("\n%d",x);
    return 0;
}

OUTPUT: 5 5

Note: I know that I should not be referencing a variable that is local to a function but I tried it on purpose and got this peculiar output. I assumed that it won't work even for the first cout statement because the sum variable to which it is referenced is getting destructed with the return of the function. But the case is just the opposite!

0 Answers
Related