Strange statement fails on bool booleans and variables

Some of the statements in my code just started acting strange, and I was wondering if anyone had a similar situation before. A short piece of code, for example:

#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, changing the code a bit:

 A::someFunction(){ assert(this->isM); assert(this->isN); ... } 

statements pass without problems, and the function ends normally. Functional processing is usually expected functionality since bool variables are set before the actual call to someFunction() .

As an additional question, is there a better way to make statements in C ++? I grew up in C and I still use C-style statements. I just scratched the surface of Google, but found nothing, hinting at something new.

Oh, and if necessary, I can provide more context for the class and variables if this is not enough for someone to recognize the problem situation. The bool variables are actually set in an instance of the subclass, and someFunction is one of the rare functions implemented in the class A interface, but since this complicates the issue, I will only edit it in more detail if the community considers this relevant.

+6
source share
1 answer

Booleans are uninitialized. They can take any value. The behavior here is undefined. To illustrate this using the 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 conclusion:

 121, 0 244, 31 

or by running again

 192, 0 244, 127 

or, optimizing with -O3 , a bunch of zeros.

+3
source

Source: https://habr.com/ru/post/912305/


All Articles