No, this does not invoke undefined behavior and the expected print value is 5.
Since you declared your function as void f(int& x)
the int&
is a reference type and changes the value of the variable it is bound to and does not copy it.
Be aware of what is a real example of undefined behavior with references:
int& f() {
int x = 5;
return x; //return a reference of a variable that will not exist
//after f finished
}
int main() {
std::cout << f() << std::endl; //undefined behavior
}
This is undefined behavior since references do not take responsibility of keeping allocated data valid that they refer to, the reference just changes and reads values if they are valid. So after f()
is finished the reference is going to point to invalid memory.