I have the following code:
#include <iostream>
void f(int &x) {
x = 5;
}
int main() {
int x;
f(x);
std::cout << x << std::endl;
return 0;
}
Does this code invoke undefined behavior in C++? g++ compiles it without any warnings and the code prints out 5
(as expected?).
There is no undefined behavior in this code. It would be undefined to use an uninitialized variable before it has been assigned a value, but it is well-defined to pass around a reference and to perform an assignment via a reference.
Undefined behaviour occurs when an indeterminate value is produced by an evaluation, with a few exceptions (see §8.5/12 of the C++14 standard).
In this case, the value of x
isn't used until after x
has been assigned to, so this code is fine. The value of x
is not accessed in order to bind a reference to it. (However, beware: an int
can also be bound to a const double&
, in which case the value would be accessed, and a new temporary double
object would be created from that value.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With