C++ Logo

std-proposals

Advanced search

Re: [std-proposals] On short-circuiting bool comparisons (and in general)

From: Lorand Szollosi <szollosi.lorand_at_[hidden]>
Date: Tue, 16 Sep 2025 03:14:34 +0200
Hi,

See inline:
>> using std::bool_sc; // use all operators
>> bool a, b; // initialize here
>> return a <= b; // same as: !a || b
>
> I don't understand the equivalence here.
>
> If `a` and `b` are `bool`s, how is `a <= b` ever supposed to not be
> true?
If a is true and b is false, then true<=false does not hold (because 1<=0 does not hold). So a<=b (for booleans) holds if either a is false or b is true; hence, !a || b. Mathematically, it’s implication (albeit in math we have a different notation, something we cannot use here).

> Is it something that happens if `a` is constructed from an
> unsigned integer value that's larger than `b`? And if that's the case,
> how would it be equivalent to `!a || b`?
No, here a and b are bools.
Observe that:
constexpr bool a = true, b = false;
static_assert(!(a<=b)); // this holds
In all other cases, it’s true.

> Also, it's unclear where the "short-circuit" nature of these operators
> comes in. Short-circuiting, in the context of C++ boolean operators,
> typically means that you don't have to evaluate both operands. If you
> have two expressions X and Y that are contextually convertible to
> `bool`, `X || Y` means that `Y` will only be evaluated if `X` is
> false.
Yes, it’s exactly the same here. If you write (for two expressions X and Y), X <= Y, and you figure out that X evaluates to false, then Y does not need to be evaluated. Technically, we could say the same about Y evaluating to true, but _if_ we wanted to use it for implication, which models an if-then, it’s perhaps better not to.
Alas, X is evaluated and, _if_ it’s true, Y is evaluated (and its truth value becomes the result); otherwise, it’s false.
For X>=Y, X is evaluated and, _if_ it’s false, Y is evaluated _and negated_ and that becomes the result; otherwise, it’s true.

> And note that this is "contextually convertible to `bool`". Which
> means that it works on expressions that don't evaluate to a `bool`
> type. So again, it's unclear how that's supposed to work.
I’d say it’s for bools, maybe even explicit bools. It’d make little sense to interfere with integer comparison, or even int-to-bool, bool-to-int comparison. The first part of the writing is strictly for bools.

Thanks,
-lorro

Received on 2025-09-16 01:14:49