Returning a link from a function and changing it

#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 change Aand Bon f()=f(), I get 5 in both compilers. What is the matter here? This behavior is undefined. If so, why?

+3
source share
1 answer

This is undefined because in this code:

f() = f() + 1;

it is not defined which call f () comes first.

+5
source

Source: https://habr.com/ru/post/1758534/


All Articles