Andrew Sun
Andrew Sun

Reputation: 4231

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

Upvotes: 8

Views: 1812

Answers (3)

Djeefther Souza
Djeefther Souza

Reputation: 127

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.

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119184

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

Upvotes: 6

Remy Lebeau
Remy Lebeau

Reputation: 596307

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.

Upvotes: 13

Related Questions