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

前端 未结 5 1661
终归单人心
终归单人心 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:18

    OP is looking at some old coding idiom - which made some sense BITD (back-in-the day).

    1. A primary use of !! was to handle C implementations that converted the expression in an if(expr) to int rather than testing against zero.

    Consider what happens when expr is converted to int and then tested against 0. (Since C89, this is non-conforming as the test should be a direct test against 0)

    int i;
    long li;
    double d;
    
    // no problems
    if (i & 5) ...
    if (d > 4.0) ...
    
    // problems
    if (li & 0x10000) ...  (Hint: int is 16-bit)
    if (d)                 (d might have a value outside `int` range.
    
    // fix
    if (!!(li & 0x10000))
    if (!!d)
    

    So on pre C89 compliers and non-conforming C89 and later, using !! coped with that weakness. Some old habits take a long time to die.

    1. In early C++, there was no bool type. So code that wanted to test for trustfulness needed to use the !! idiom

      class uint256;  // Very wide integer
      uint256 x;
      
      // problem  as (int)x may return just the lower bits of x
      if (x) 
      
      // fix
      if (!!x) 
      
    2. What happens with C++ today (I know this is a C question) when there is no (bool) operator defined, is not the (int) operator used? This results in the same problem as #2. As for many early years C and C++ code bases were kept in sync, using !! had relevance with constructs like if (!!x).


    Using !! works today but has certainly fallen out of favor as it solves problem that no longer occurs with any significant frequency.

提交回复
热议问题