Undefined Behavior and Sequence Points Revisited
In this sequel to the topic "Undefined Behavior and Sequence Points," we delve into the behavior of expressions involving user-defined types.
User-Defined Types and Undefined Behavior
Consider the following expression involving a user-defined type Index:
i += ++i;
The behavior of this expression with built-in types is undefined. However, does it still invoke undefined behavior if i is of type Index?
No, it does not. This is because the expression becomes equivalent to:
i.operator+=(i.operator++());
Since overloaded operators are functions, the normal sequencing rules apply. A sequence point exists after the evaluation of i.operator (), so the subsequent modification of i in i.operator =() does not violate any undefined behavior rules.
Similarly, the expressions i.add(i.inc()); and i are well-defined. The first expression is equivalent to:
i.operator+=(i.operator++());
And the second expression is equivalent to:
(i.operator++()).operator++()).operator++();
Each of these expressions has a sequence point after the evaluation of the operator () expression, ensuring that the object i is not modified twice between consecutive sequence points.
Subscript Operator Overload
The expression:
a[++i] = i;
where a is a user-defined type that overloads the subscript operator, is also well-defined. The increment operator returns an Index object, which is then used to index the a array. The assignment operator = is equivalent to the operator[]() method, which is a function call. Therefore, the sequencing rules apply, and a sequence point exists after the evaluation of i. Consequently, the expression is well-defined.
Additional Points
The above is the detailed content of Does Overloading Operators in C Eliminate Undefined Behavior in Expressions like `i = i`?. For more information, please follow other related articles on the PHP Chinese website!