6

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Patrick José Pereira
  • 1,613
  • 2
  • 11
  • 12
  • @t.niese If possible, I would like to know in both C and C++ :) – Patrick José Pereira Apr 06 '20 at 18:43
  • The concept of sequence points was abolished from C++ in 2011. The cppreference page needs to be updated. I am removing the C++ tag from this question but feel free to add a new question. – Brian Bi Apr 06 '20 at 18:49
  • 2
    @Brian -- the **concept** of sequence points wasn't abolished; the **terminology** was changed. The intention was to preserve the rules that had applied previously. – Pete Becker Apr 06 '20 at 18:53
  • @PeteBecker I agree the intent was to preserve the rules that had applied previously, but the concept also did change to a more general one. – Brian Bi Apr 06 '20 at 18:54
  • @PatrickJoséPereira *Re: "i = i++ + 1 is UB"* Until C++17 – Ardent Coder Apr 06 '20 at 18:58

2 Answers2

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

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.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53