C++ Logo

std-discussion

Advanced search

Re: Comparison operators

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Mon, 19 Dec 2022 17:10:18 +0000
On Mon, 19 Dec 2022 at 17:56, Lénárd Szolnoki via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> Hi
>
> On 19 December 2022 14:32:32 GMT, Vladimir Grigoriev via Std-Discussion <
> std-discussion_at_[hidden]> wrote:
> >
> >There is another unclear phrase in the C++ 20 Standard relative to
> comparison operators.
> >
> >«3 The return value V of a defaulted == operator function with parameters
> x and y is determined by comparing corresponding elements xi and yi in the
> expanded lists of subobjects for x and y (in increasing index order) until
> the first index i where xi == yi yields a result value which, when
> contextually converted to bool, yields false. If no such index exists, V is
> true. Otherwise, V is false.»
> >
> >What does the last statement « Otherwise, V is false.»» mean?
>
> My reading in pseudocode it would look something like:
>
> /* ...comparing corresponding elements xi and yi in the expanded lists of
> subobjects for x and y (in increasing index order) until the first index i
> where xi == yi yields a result value which, when contextually converted to
> bool, yields false. */
> bool mismatch_found = false;
> for (size_t idx=0; idx < member_count; ++idx) {
> if (not (lhs_members[idx] == rhs_members[idx]) {
> mismatch_found = true;
> break;
> }
> }
>
> // If no such index exists, ...
> if (not mismatch_found) {
> return true; // ... V is true.
> } else { // Otherwise, ...
> return false; // ... V is false.
> }
>
> The first part describes the side effects of the defaulted definition, and
> the short-circuiting in particular. The second part describes the returned
> value.
>
> Obviously this can be written more clearly and concisely in pseudocode.
> Would be nice if it could similarly be simplified in English.
>

Close, but `not` doesn't necessarily do what it should. I'd say this would
be more correct and idiomatic:

/* ...comparing corresponding elements xi and yi in the expanded lists of
subobjects for x and y (in increasing index order) until the first index i
where xi == yi yields a result value which, when contextually converted to
bool, yields false. */
size_t idx=0;
for (; idx != member_count; ++idx) {
    if (lhs_members[idx] == rhs_members[idx]) {
        ;
    } else {
        break;
    }
}

// If no such index exists, ...
if (idx == member_count) {
    return true; // ... V is true.
} else { // Otherwise, ...
    return false; // ... V is false.
}

Received on 2022-12-19 17:10:30