如果使用(!!(表达式)),而不是如(表达式) [英] Using if (!!(expr)) instead of if (expr)

查看:265
本文介绍了如果使用(!!(表达式)),而不是如(表达式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读德州仪器为他们 SensorTag 我碰到下面的代码片段来提供的例子code

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

void SensorTagIO_processCharChangeEvt(uint8_t paramID) { 
    ...

    if (!!(ioValue & IO_DATA_LED1)) {
        PIN_setOutputValue(hGpioPin, Board_LED1, Board_LED_ON);
    } else {
        PIN_setOutputValue(hGpioPin, Board_LED1, Board_LED_OFF);
    }

    if (!!(ioValue & IO_DATA_LED2)) {
        PIN_setOutputValue(hGpioPin, Board_LED2, Board_LED_ON);
    } else {
        PIN_setOutputValue(hGpioPin, Board_LED2, Board_LED_OFF);
    }

    if (!!((ioValue & IO_DATA_BUZZER))) {
        Clock_start(buzzClockHandle);
    }
    ...
}

的声明是这样的(在同一个文件)。

The declaration is like this (in the same file).

#define IO_DATA_LED1   0x01
static uint8_t ioValue;

确实如果(!(ioValue&安培; IO_DATA_LED1))提供超过任何优势,如果(ioValue&安培; IO_DATA_LED1)

推荐答案

将逻辑不()运算符两次已经正常化值的目的是0或NBSP; 1。在if语句,这并没有任何区别的控制前pression。 if语句只关心价值为零或非零,小 !! 舞蹈是完全无用的。

Applying the logical not (!) operator twice has the purpose of normalising a value to be either 0 or 1. In a control expression of an if-statement, that doesn't make any difference. The if-statement only cares about the value being zero or nonzero, the little !! dance is completely useless.

某些编码风格指南可能强制要求这种舞蹈,这可能是为什么你张贴的TI code做它的原因。我还没有看到任何这样做虽然。

Some coding style guides might mandate this kind of dance, which could be the reason why the TI code you posted does it. I haven't seen any that do so though.

这篇关于如果使用(!!(表达式)),而不是如(表达式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆