Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the opposite value of a bool variable in C++

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++?

like image 711
Terry Li Avatar asked Nov 10 '11 20:11

Terry Li


People also ask

How do you get the opposite of a boolean value?

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 .

How do you flip a boolean variable?

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.

What is the return value of bool?

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.

Does C have bools?

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.


2 Answers

Just use the ! operator:

bool x = // something

bool y = !x;  //  Get the opposite.
like image 83
Mysticial Avatar answered Nov 01 '22 07:11

Mysticial


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.

like image 40
Cam Avatar answered Nov 01 '22 05:11

Cam