Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is undefined behavior to declare a variable while passing by reference?

Tags:

c

From cppreference:

Between the previous and next sequence point a scalar object must have its stored value modified at most once by the evaluation of an expression, otherwise the behavior is undefined.

Code example:

int a = store_and_return_value(&a);

For both C and C++.

like image 516
Patrick José Pereira Avatar asked Oct 15 '22 04:10

Patrick José Pereira


1 Answers

This does not exhibit undefined behavior.

Section 6.5.2.3p10 of the C standard states:

There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function

So given your line of code:

int a = store_and_return_value(&a);

The call to the function store_and_return_value introduces a sequence point. Assuming there is a line similar to *arg = 123; in the function, there is also a sequence point after this statement.

So any statement inside of store_and_return_value that dereferences and writes the passed in pointer is sequenced after a is formally initialized. So regardless of what the body of store_and_return_value contains the program is well defined.

like image 177
dbush Avatar answered Oct 19 '22 09:10

dbush