Suggestion for extra jassert() functionality

I’ve ran several times into a situation, where it would have been useful to have an assertion, which was conditional in nature. See the following idea:

if (if_this_is_true)
    jassert(test_this_and_that);

I.e. the “if” statement was a prerequisite for the test to be valid.

So I would propose an extra jassert() method, which would let the user add that prerequisite test for the assertion. The above example would then be written in the form of:

jassertIf(if_this_is_true, test_this_and_that);

Could something like that be added into JUCE? Maybe just add the below piece of code into JUCE:

#define jassertIf(prerequisite, expression)     JUCE_BLOCK_WITH_FORCED_SEMICOLON (if (prerequisite) if (! (expression)) jassertfalse;)

Ignore all this, made an obvious logic mistake that corrected by @basteln below

Why not just:

jassert(if_this_is_true && (test_this_and_that))

If if_this_is_true is false it will shortcut and won’t even evaluate the 2nd part.

It’s not really that much different than what you’ve suggested, maybe a tiny bit uglier.

2 Likes
jassert(if_this_is_true && test_this_and_that);

Am I missing something?

EDIT: Yes, I was clearly missing another cup of coffee this morning. This jassert suggestion doesn’t satisfy OP’s requirements. Doh.

Should be (as per basteln’s sugggestion):

jassert(!if_this_is_true || test_this_and_that);
2 Likes

Snap!

You beat me to it by a few seconds! :slightly_smiling_face:

Ah, I forgot that C++ is guaranteed to skip the evaluation of the second part in that case.

This can be simplified to:

if (prerequisite && !expression) jassertfalse;

Or:

jassert(!prerequisite || expression);
jassert(!if_this_is_true || test_this_and_that);

The !prerequisite || expression means: “If prerequisite is false, pass without checking expression. If prerequisite is true, check expression”.

Note that this is different from the suggestion so far:

jassert(if_this_is_true && test_this_and_that);

This one would fail the assertion if if_this_is_true is false. But you want to skip the entire jassert check in that case.
It would also skip (pass) the check if if_this_is_true is true. Which is the opposite from what you asked.

2 Likes