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