The behavior of a bool pointer element is different when set to true vs false

I am using a simple bool pointer class element. Assignment of false or. true behaves differently - see comments in code. I subtract one to check the other below.

I use compiler call g++ -o basic basic.cpp

class Test
{
public:
    int a;
    bool* abool;
};


int main() {
    Test t;

    //t.abool = false;              // WORKS
    //t.abool = true;               // ERROR: cannot convert 'bool' to 'bool*' in assignment - expected IMO; 

    // this should work for both values IMO
    //*(t.abool) = true;            // Segmentation fault
    //*(t.abool) = false;           // Segmentation fault



    cout << t.abool << endl;

    return 0;
}
+3
source share
4 answers

, false 0. , t.abool = 0;, abool NULL. true 1, , . ( IMO) seg, , undefined.

+10

bool* , -.

( false ) bool:

bool test;

t.abool = 0; // or NULL
t.abool = &test;

bool, bool :

*t.abool = true;
*t.abool = false;
+6

false works because false is probably treated like 0in g ++

+1
source

Any literal with a numeric type and a null value can be implicitly converted to a null pointer. boolis a numeric type, and falsehas a value of 0. Nonzero values ​​(for example, true) cannot be implicitly converted to a pointer.

+1
source

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


All Articles