As an exercise, I would like to check, in a single assert
, if I have seen some (boolean) state before. Seeing it never is OK, seeing it once is OK, but seeing it twice should raise an assertion. (To be exact, seeing anything after seeing it once should raise an assertion.)
I have tried assert(!(seen & (seen |= is_here)));
- however, this behaves very inconsistently across compilers.
- At https://www.programiz.com/cpp-programming/online-compiler/, it just works.
- At https://replit.com/languages/cpp, it works with helpful warning (
-Wunsequenced
) - On MSVC, the third call fails already
#include <iostream>
#include <assert.h>
int main() {
bool seen = false;
bool is_here;
is_here = false;
// these shall pass
assert(!(seen & (seen |= is_here)));
assert(!(seen & (seen |= is_here)));
is_here = true;
// this shall pass, but fails in MSVC
assert(!(seen & (seen |= is_here)));
// after that, this shall pass
assert( (seen & (seen |= is_here)));
is_here = false;
// same as this
assert( (seen & (seen |= is_here)));
std::cout << "Done.";
return 0;
}
I think I am hitting a wall of undefined behavior, so I have tried rewriting my expression, with no success. (I guess this may be more of a logical problem than a programming one.) I have tried rewriting using &&
or ||
, which have sequence points, but since these are short-circuiting as well, I haven't found a correct expression yet.