Why use !! when converting int to bool?

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

    Another option is the ternary operator which appears to generate one line less of assembly code (in Visual Studio 2005 anyways):

    bool ternary_test = ( int_val == 0 ) ? false : true;
    

    which produces the assembly code:

    cmp DWORD PTR _int_val$[ebp], 0
    setne   al
    mov BYTE PTR _ternary_test$[ebp], al
    

    Versus:

    bool not_equal_test = ( int_val != 0 );
    

    which produces:

    xor eax, eax
    cmp DWORD PTR _int_val$[ebp], 0
    setne   al
    mov BYTE PTR _not_equal_test$[ebp], al
    

    I know it isn't a huge difference but I was curious about it and just thought that I would share my findings.

提交回复
热议问题