In a previous installment, "Undefined Behavior and Sequence Points," we discussed the potential undefined behavior associated with the expression:
i += ++i;
When i is a built-in type, this expression invokes undefined behavior because the object i is modified twice between consecutive sequence points.
However, if i is a user-defined type, such as the Index class defined below:
class Index { int state; public: Index(int s) : state(s) {} Index& operator++() { state++; return *this; } Index& operator+=(const Index & index) { state+= index.state; return *this; } operator int() { return state; } Index & add(const Index & index) { state += index.state; return *this; } Index & inc() { state++; return *this; } };
Would the expression i = i still invoke undefined behavior?
Surprisingly, no. Expression i = i with a user-defined type i does not invoke undefined behavior because overloaded operators are considered functions in C . According to section 1.9.17 of the C ISO standard:
When calling a function (whether or not the function is inline), there is a sequence point after the evaluation of all function arguments...
Therefore, the calls to the operator and operator = functions introduce sequence points, preventing undefined behavior.
The expression a[ i] = i is also well-defined when a is a user-defined type with an overloaded subscript operator, as it is considered a function call with a sequence point after evaluating the i expression.
In C 03, the expression i is well-defined, as it is effectively equivalent to:
((i.operator++()).operator++()).operator++();
With each function call introducing a sequence point, making the expression well-defined.
The above is the detailed content of Is `i = i` Always Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!