-2

This started from a joke:

Interviewer: What is the difference between C and C++?
Candidate: ONE

My question is whether the expressions abs(C++ - C) and abs(C - C++) invokes undefined behavior or not?

Quixotic
  • 2,424
  • 7
  • 36
  • 58

3 Answers3

4

It depends on the type of C, but at the best (a user defined type, where ++ is a function), it is unspecified whether the second C is evaluated before or after the evaluation of C.operator++.

Of course, for a built-in type, the expression is undefined behavior, and for a user defined type, the final results will also depend on how the user defined operator++, as well as the compiler dependent order of evaluation.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
3

Yes, this is undefined behaviour. The compiler will not make any promises on when the increment will happen if you reuse the same variable in the statement.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • It's only undefined behavior if `C` has a built-in type. Otherwise, it's only unspecified (and with a limited set of possible values---supposing that the user defined `operator++` is deterministic). – James Kanze Feb 13 '14 at 15:53
0

yes this is UB. From C99, Section 6.5

An expression is a sequence of operators and operands that specifies computation of a value

Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified

Therefore the is no guarantee in the express C++ - C when the post increment is executed.

Jimbo
  • 4,352
  • 3
  • 27
  • 44