Is passing an uninitialized variable in the function parameter list clearly defined?

I have code that 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 behavior here? I suspect it might be, since I take a copy of the uninitialized double value when passing f to bar . However, I do not use the passed double , but since the if block will not start.

In addition, it would be all right if I passed a double by reference:

 void bar(bool b, double& f) 

Then I do not "use" the uninitialized variable, but simply refer to it.

+6
source share
1 answer

Yes, the behavior is undefined. When passing to the list of function parameters, you take a copy of the value of the uninitialized double .

Passing by reference is well defined since all you do is bind to that double link. Of course, the access behavior for this link will be undefined.

N4140:

[dcl.init]

12 ... If an undefined value is obtained by evaluating, the behavior is undefined, except in the following cases:

(Inappropriate text omitted from unsigned narrow character types)

+9
source

Source: https://habr.com/ru/post/979452/


All Articles