Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

expression

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; 

Does if (!!(ioValue & IO_DATA_LED1)) offer any advantage over if (ioValue & IO_DATA_LED1)?

like image 515
Yaseen Avatar asked Feb 20 '16 12:02

Yaseen


1 Answers

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.

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.

like image 127
fuz Avatar answered Sep 23 '22 17:09

fuz