Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it undefined behavior to pass-by-reference uninitialized variable?

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?).

like image 636
Andrew Sun Avatar asked Feb 10 '16 03:02

Andrew Sun


2 Answers

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.

like image 129
Remy Lebeau Avatar answered Nov 06 '22 03:11

Remy Lebeau


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.)

like image 26
Brian Bi Avatar answered Nov 06 '22 05:11

Brian Bi