C++ Logo

std-proposals

Advanced search

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

From: Lorand Szollosi <szollosi.lorand_at_[hidden]>
Date: Mon, 15 Sep 2025 20:17:39 +0200
Hi,

Is there a reason why we don’t have at least opt-in short-circuit for bool comarisons? I mean, I understand that currently it’s considered as int comparison and we need bacward compatibility; however, I don’t see any reason why we could not have a namespace for such operators:

using std::bool_sc; // use all operators
bool a, b; // initialize here
return a <= b; // same as: !a || b

using std::bool_sc::operator<; // use only operator<
bool a, b; // initialize here
return a < b; // same as: !a && b

Or even, albeit that’s a long shot:
using std::bool_sc; // use all operators
bool a, b; // initialize here
return a + b; // either: a || b OR b || a
return a * b; // either: a && b OR b && a
The latter could be implementation-defined behavior, giving the optimizer a possibility to generate the better code.

This trivially solves e.g. ‘implies’ operator (of which ther’s been already a proposal), but is also about the genericity: instead of having to use some specific operators, we could always use the best fit (and not have to worry about which argument is evaluated first when looking into the codes in most cases, which might make it easier for beginners). The con is non-deterministic behavior for the latter two (which we also have elsewhere, e.g., function arguments) and the less-than-optimal a<=b syntax for ‘implies’ (which, if problematic, we can work around locally, using something like #define for the operator, either with a unicode arrow or IMPLIES, as preferred).

To go even further:
In general, I think we currently miss some kind of ‘formula visitor’ capability of operators. Currently, if you wanted to write short-circuiting, you either have to accept lambdas explicitly (rather verbose), have expression trees (completely different types, wrappers), or resort to exceptions (which are not designed for this purpose as those are for exceptional situations; it’d be slow and difficult to debug). While I’m far from claiming to have a one-size-fits-all solution, it could be addressed I think by some kind of lazy parameter support (that, instead of taking evaluated arguments, could consider argument as callable and evaluate only when used - similarly to call-by-name). This could make most short-circuit issues user-space implementable (well, on custom types at least).

Thanks,
-lorro

Received on 2025-09-15 18:17:53