Some assertions in my code just started acting strangely, and I was wondering if anyone had a similar situation before. A short code snippet like:
#include <cassert>
class A{
protected:
bool isM, isN;
public:
void someFunction();
};
A::someFunction(){
assert (this->isM && this->isN);
...
}
produces an assertion failed
result. On the other hand, after changing the code just slightly:
A::someFunction(){
assert(this->isM);
assert(this->isN);
...
}
the assertions pass with no problem and function finishes normally. Function finishing normally is the expected functionality, since the bool
variables are set before the actual call to someFunction()
.
As an additional question, is there a better way of doing assertions in C++? I've grown up on C, and am still using the C-style assertions. I've just scratched Google surface on this, but found nothing hinting there's anything new.
Oh, and if needed, I can provide more context for the class and the variables if this is not enough for anyone to recognize the problematic situation. The bool
variables are actually set in an instance of a subclass, while someFunction
is one of the rare functionalities implemented in the class A
interface, but since this complicates the question, I will only edit it in in more detail if the community thinks it relevant.
The booleans are uninitialized. They could take any value. The behaviour here is undefined. To illustrate that, using a gcc 4.7 snapshot on ubuntu 11.10:
#include <iostream>
struct A {
bool a, b;
};
int main() {
A a0;
std::cout << a0.a << ", " << a0.b << "\n";
A a1;
std::cout << a1.a << ", " << a1.b << "\n";
}
produces this output:
121, 0
244, 31
or, running again,
192, 0
244, 127
or, optimizing with -O3
, a bunch of zeroes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With