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

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

Upvotes: 6

Views: 285

Answers (2)

dbush
dbush

Reputation: 224917

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.

Upvotes: 4

Ardent Coder
Ardent Coder

Reputation: 3995

int a = scanf("%d", &a); does not exhibit undefined behaviour.

These are well-defined steps:

  1. An int variable is created on stack named a

  2. scanf reads a value from the standard input into a

  3. scanf returns a value

  4. This return value is assigned to a.

The final value of a is decided by the return value of scanf, either 1 (if that one variable a was read successfully) or 0 (read failed).

Edit:

The answer was written before the question was edited to

int a = store_and_return_value(&a);

The same reasoning goes here.

Upvotes: 1

Related Questions