Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning reference from a function and modifying it

Tags:

c++

reference

#include<iostream>
int& f(){
 static int x = 0;
 x++;
 return x;
}

int main(){

  f() += 1; //A

 f() = f() + 1; //B
 std::cout << f();
}

The above code outputs 6 on gcc and 5 on MSVC. Now when I modify A and B to f()=f() I get 5 on both compilers. What is the big deal here? Is the behavior undefined. If yes , why?

like image 831
Samuel Avatar asked Apr 16 '26 08:04

Samuel


1 Answers

It is undefined, because in this code:

f() = f() + 1;

it is not defined which call to f() happens first.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!