Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing an uninitialised variable in a function parameter list well-defined?

I have some code which essentially boils down to the following:

void bar(bool b, double f)
{
    if (b){
        double g = f;
    }
}

void foo()
{
    double f;
    bool b = false;
    bar(b, f);
}

Is there any undefined behaviour here? I suspect there may be since I'm taking a value copy of the uninitialised double when passing f to bar. That said, I'm not making use of the passed double though since the if block will not run.

Furthermore, would everything be fine if I were to pass the double by reference:

void bar(bool b, double& f)

Then I'm not "using" an uninitialised variable but am simply referring to it.

like image 367
P45 Imminent Avatar asked Dec 11 '14 11:12

P45 Imminent


1 Answers

Yes, the behaviour is undefined. You are taking a value copy of the uninitialised double when passing it in the function parameter list.

Passing by reference is well-defined since all you're doing is binding that reference to that double. Of course, the behaviour of accessing that reference would be undefined.

N4140:

[dcl.init]

12 ... If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

(Irrelevant text omitted, pertaining to unsigned narrow character types)

like image 83
Bathsheba Avatar answered Sep 22 '22 01:09

Bathsheba