Why use !! when converting int to bool?

前端 未结 10 1832
梦谈多话
梦谈多话 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:46

    Historically, the !! idiom was used to ensure that your bool really contained one of the two values expected in a bool-like variable, because C and C++ didn't have a true bool type and we faked it with ints. This is less of an issue now with "real" bools.

    But using !! is an efficient means of documenting (for both the compiler and any future people working in your code) that yes, you really did intend to cast that int to a bool.

提交回复
热议问题