Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange assert fail on logical and of bool variables

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.

like image 712
penelope Avatar asked Apr 03 '12 09:04

penelope


1 Answers

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.

like image 60
juanchopanza Avatar answered Sep 29 '22 05:09

juanchopanza