Why use !! when converting int to bool?

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

    The answer of user143506 is correct but for a possible performance issue I compared the possibilies in asm:

    return x;, return x != 0;, return !!x; and even return boolean_cast(x) results in this perfect set of asm instructions:

    test    edi/ecx, edi/ecx
    setne   al
    ret
    

    This was tested for GCC 7.1 and MSVC 19 2017. (Only the boolean_converter in MSVC 19 2017 results in a bigger amount of asm-code but this is caused by templatization and structures and can be neglected by a performance point of view, because the same lines as noted above may just duplicated for different functions with the same runtime.)

    This means: There is no performance difference.

    PS: This boolean_cast was used:

    #define BOOL int
    // primary template
    template< class TargetT, class SourceT >
    struct boolean_converter;
    
    // full specialization
    template< >
    struct boolean_converter
    {
      static bool convert(BOOL b)
      {
        return b ? true : false;
      }
    };
    
    // Type your code here, or load an example.
    template< class TargetT, class SourceT >
    TargetT boolean_cast(SourceT b)
    {
      typedef boolean_converter converter_t;
      return converter_t::convert(b);
    }
    
    bool is_non_zero(int x) {
       return boolean_cast< bool >(x);
    }
    

提交回复
热议问题