Home >Backend Development >C++ >Does Overloading Operators in C Eliminate Undefined Behavior in Expressions like `i = i`?

Does Overloading Operators in C Eliminate Undefined Behavior in Expressions like `i = i`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 00:22:09664browse

Does Overloading Operators in C   Eliminate Undefined Behavior in Expressions like `i  =   i`?

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 number of sequence points associated with an expression does depend on the types of operands involved, as the case of i = i demonstrates.
  • In C 03, the expression i is well-defined.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn