What does the ^ operator do to a BOOL?

空扰寡人 提交于 2020-01-30 06:55:46

问题


What does this statement mean?

isChecked = isChecked ^ 1;

isChecked is a BOOL.


回答1:


it will XOR isChecked with 1 so I suppose true ^ 1 = 0(false) and false ^1 = 1(true)




回答2:


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.




回答3:


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.




回答4:


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




回答5:


^ 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.




回答6:


"^" 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




回答7:


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



来源:https://stackoverflow.com/questions/10793720/what-does-the-operator-do-to-a-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!