Why use !! when converting int to bool?

前端 未结 10 1845
梦谈多话
梦谈多话 2020-11-30 22:37

What can be a reason for converting an integer to a boolean in this way?

bool booleanValue = !!integerValue;

instead of just



        
10条回答
  •  没有蜡笔的小新
    2020-11-30 22:37

    A bool can only have two states, 0, and 1. An integer can have any state from -2147483648 to 2147483647 assuming a signed 32-bit integer. The unary ! operator outputs 1 if the input is 0 and outputs 0 if the input is anything except 0. So !0 = 1 and !234 = 0. The second ! simply switches the output so 0 becomes 1 and 1 becomes 0.

    So the first statement guarantees that booleanValue will be be set equal to either 0 or 1 and no other value, the second statement does not.

提交回复
热议问题