While reading the example code provided by Texas Instruments for their SensorTag I came across the following snippet.
void SensorTagIO_processCharChangeEvt(uint8
Although silencing the compiler warning for the bit-wise &
is the most likely, this looks like it could also be the result of a refactoring to add enums for readability from:
PIN_setOutputValue(int,int,bool); //function definition
PIN_setOutputValue(hGpioPin, Board_LED1,!!(ioValue & IO_DATA_LED1));
PIN_setOutputValue(hGpioPin, Board_LED2,!!(ioValue & IO_DATA_LED2));
//note: the !! is necessary here in case sizeof ioValue > sizeof bool
//otherwise it may only catch the 1st 8 LED statuses as @M.M points out
to:
enum led_enum {
Board_LED_OFF = false,
Board_LED_ON = true
};
PIN_setOutputValue(int,int,bool); //function definition
//...
PIN_setOutputValue(hGpioPin, Board_LED1,!!(ioValue & IO_DATA_LED1)?Board_LED_ON:Board_LED_OFF);
PIN_setOutputValue(hGpioPin, Board_LED2,!!(ioValue & IO_DATA_LED2)?Board_LED_ON:Board_LED_OFF);
Since that exceeded the 80 character limit it was then refactored to
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);
}
Personally I would have preferred the initial version for readability, but this version is common when lines of code are used as a metric (I'm surprised it didn't declare variables for each state, set each state separately and then use that).
The next version of this "Best Practice" code might look like:
bool boardled1State;
bool boardled2State;
//...
boardled1State = !!(ioValue & IO_DATA_LED1);
boardled2State = !!(ioValue & IO_DATA_LED2);
//...
if (boardled1State) {
PIN_setOutputValue(hGpioPin, Board_LED1, Board_LED_ON);
} else {
PIN_setOutputValue(hGpioPin, Board_LED1, Board_LED_OFF);
}
if (boardled2State) {
PIN_setOutputValue(hGpioPin, Board_LED2, Board_LED_ON);
} else {
PIN_setOutputValue(hGpioPin, Board_LED2, Board_LED_OFF);
}
//... and so on
All of that could have been done like this:
for (int i=0;i