Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence point from function call?

This is yet another sequence-point question, but a rather simple one:

#include <stdio.h>
void f(int p, int) {
  printf("p: %d\n", p);
}

int g(int* p) {
  *p = 42;
  return 0;
}

int main() {
  int p = 0;
  f(p, g(&p));
  return 0;
}

Is this undefined behaviour? Or does the call to g(&p) act as a sequence point?

like image 861
lucasmrod Avatar asked Aug 29 '13 16:08

lucasmrod


People also ask

What is sequence points?

A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.

Is comma a sequence point?

The comma operator has the lowest precedence of any C operator, and acts as a sequence point.

What is the order of evaluation?

Order of evaluation refers to the operator precedence and associativity rules according to which mathematical expressions are evaluated.

What is sequence point in C++?

Sequence point rules (until C++11) A sequence point is a point in the execution sequence where all side effects from the previous evaluations in the sequence are complete, and no side effects of the subsequent evaluations started.


Video Answer


2 Answers

No. It doesn't invoke undefined behavior. It is just unspecified, as the order in which the function arguments are evaluated is unspecified in the Standard. So the output could be 0 or 42 depending on the evaluation order decided by your compiler.

like image 144
Nawaz Avatar answered Oct 05 '22 06:10

Nawaz


The behavior of the program is unspecified since we don't know the order of evaluation of the function arguments, from the draft C++ standard 1.9 Program execution paragraph 3:

Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. [...]

and all side effects from the arguments are sequenced before the function is entered, from section 5.2.2 Function call paragraph 8:

[ Note: The evaluations of the postfix expression and of the argument expressions are all unsequenced relative to one another. All side effects of argument expression evaluations are sequenced before the function is entered (see 1.9). —end note ]

As for C both points are covered in the C99 draft standard in section 6.5.2.2 Function calls paragraph 10:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

So in both C and C++ you can end up with either f(0,0) or f(42,0).

like image 42
Shafik Yaghmour Avatar answered Oct 05 '22 08:10

Shafik Yaghmour