Using if (!!(expr)) instead of if (expr)

前端 未结 5 1725
终归单人心
终归单人心 2021-02-03 17:05

While reading the example code provided by Texas Instruments for their SensorTag I came across the following snippet.

void SensorTagIO_processCharChangeEvt(uint8         


        
5条回答
  •  半阙折子戏
    2021-02-03 17:32

    The expression !!x, or !(!x), means 1 if x is a true value (a nonzero number or a nonnull pointer), otherwise 0. It is equivalent to x != 0, and it's nearly the same as C99 (_Bool)x but available in compilers that predate C99 or whose developers have chosen not to implement C99 (such as cc65 which targets the MOS 6502).

    The conditional as a whole is equivalent to the following:

    if (ioValue & IO_DATA_LED1) {
        /* what to do if the IO_DATA_LED1 bit is true */
    } else {
        /* what to do if the IO_DATA_LED1 bit is false */
    }
    

    In C, it means "if the bitwise AND of those two values is nonzero, execute the block."

    But some coding style guides might prohibit a bitwise AND (&) at the top level of an if statement's condition, assuming it to be a typo for the logical AND (&&). It's in the same class of mistakes as using = (assignment) instead of == (equality comparison), for which many compilers offer a diagnostic. GCC Warning Options describes diagnostics like these:

    -Wlogical-op: Warn about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected.

    -Wparentheses: Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected

    Use of a paraphrase such as (a & B) != 0, (_Bool)(a & B), or !!(a & B) communicates to the compiler and to other developers that use of a bitwise operator was intentional.

    See also a related answer about !!x in JavaScript.

提交回复
热议问题