To me, a bool variable indicates either true or false.
Some bool variable was defined and initialized to a value unknown to us. I just want to get the opposite value of it. How should I do it in C++?
The "and" ( && ) operator returns true if the boolean value to its left and the boolean value to its right are true. And the "not" ( ! ) operator returns the opposite of the boolean value to its right. That is, true becomes false and false becomes true .
To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.
Return value from bool() It can return one of the two values. It returns True if the parameter or value passed is True. It returns False if the parameter or value passed is False.
C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
Just use the !
operator:
bool x = // something
bool y = !x; // Get the opposite.
bool b = false;
Correct solution:
b = !b;
Interesting solutions that you should not use:
b = b?false:true;
b ^= 1;
b = (b+1)%2;
b = 1>>b;
b = 1-b;
b = b-1;
b = -1*(b-1);
b = b+'0'+'1'-'b';
As an exercise, try to figure out why the above solutions work.
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