简体   繁体   中英

What does the ^ operator do to a BOOL?

What does this statement mean?

isChecked = isChecked ^ 1;

isChecked is a BOOL .

The "^" is an exclusive OR operation, so 0 flips to 1, and 1 flips to zero. The result should be the same as isChecked = !isChecked .

它将XOR与1检查,所以我认为是真的^ 1 = 0(假)和假^ 1 = 1(真)

Everyone is saying it XORs the bool-- that's true-- but the purpose here is that it's toggling the bool.

The advantage of doing a bitwise toggle like this is speed and the ability to fiddle bits in extreme detail.

for more Bitwise Operators

It only flips the last bit of BOOL . Not a reliable way to logically negate. If someone is crazy enough to set the a BOOL variable to some number, for example 5. Then doing ^ 1 will only flip the last bit of the value to 4, which is still evaluated to YES .

If you want to logically negate, use ! operator instead.

^ is the exclusive or operator.

In your example it is used to create a toggle - isChecked will be set only if isChecked was previously unset.

this is bitwise XOR operator and changes 0 to 1, and 1 to zero. see all opertors here .

"^" is called an exclusive OR or XOR operation. In this case, it will change boolean from true to false and vice-versa.

To learn more on this, check this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM