Home

Mathcomp

Because C++ doesn't have math-like chained comparisons.

Observed Behaviour

C/C++ sucks like this:

int p= 121;
// warning: comparison of boolean constant with arithmetic constant (39) is always true.
// Not what we want!
if (-17 < p < 39) { cout<< "foo"; } else { cout<< "bar"; } cout<< endl;

In the above the order of evaluation is:

  1. (-17 < p) → bool with the end result true.
  2. (true < 39) → bool with the end result true (both because of integer promotion and because of bool comparison, so we're double struck here).

Expected Behaviour

To be able to write a chained comparison the way it's used in MATH.

What we can do:

int p= 121;
if (something?() < -17 < p < 39) { cout<< "foo"; } else { cout<< "bar"; } cout<< endl;

So here mathcomp provides that something.

Usage

#include "mathcomp/mathcomp.hpp"

// ... in code
using mathcomp::mathcomp;
int p= 121;
if (mathcomp< -17 <= p < 39) { cout<< "foo"; } else { cout<< "bar"; }

Mathcomp supports left-to-right ordered chained comparisons that means operators < , <= and ==.

Note the use of operator< at the beginning to activate chaining comparison. Operators < , <= , == , << can be used to activate chaining.

License

mathcomp is licensed under the LGPL aka GNU Lesser Public License. License verbatim is provided in /doc/tip/LICENSE.txt. Visit also https://www.gnu.org/copyleft/lesser.html for license details and https://choosealicense.com/licenses/lgpl-3.0/ for a rundown.