-1

I am taking a compiler class and was given the equation:

int i = 5, j = 9, k;
k = f(++i) + g(++i) + j + 45;

I made a function for f and g and they both take in (int i) and return i. In the result, f and g both returned i = 7.

I was wondering why f and g both output i = 7, but not f is i = 6 and g is i = 7.

When I run it in Visual Studios, g's output runs first and then f.

Shouldn't f(++i) go first then g(++i)? Since f(++i) appears first from left to right of the equation.?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Jake
  • 313
  • 1
  • 7
  • 16

1 Answers1

1

From this:

Writing to the same variable twice without an intervening sequence point is undefined behaviour. From the spec, J.2 Undefined behaviour:

Between two sequence points, an object is modified more than once, or is modified and the prior value is read other than to determine the value to be stored (6.5).

The reference is to 6.5 Expressions, paragraph 5:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

Annex C of the C spec has a handy list of all of the sequence points:

The following are the sequence points described in 5.1.2.3:

  • The call to a function, after the arguments have been evaluated (6.5.2.2).
  • The end of the first operand of the following operators: logical AND && (6.5.13); logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).
  • The end of a full declarator: declarators (6.7.5);
  • The end of a full expression: an initializer (6.7.8); the expression in an expression statement (6.8.3); the controlling expression of a selection statement (if or switch) (6.8.4); the controlling expression of a while or do statement (6.8.5); each of the expressions of a for statement (6.8.5.3); the expression in a return statement (6.8.6.4).
  • Immediately before a library function returns (7.1.4).
  • After the actions associated with each formatted input/output function conversion specifier (7.19.6, 7.24.2).
  • Immediately before and immediately after each call to a comparison function, and also between any call to a comparison function and any movement of the objects passed as arguments to that call (7.20.5).
Community
  • 1
  • 1