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