Using Logical AND 1 when setting a variable in C

  • A+
Category:Languages

While looking through some code today, I came across an interesting(unecessary?) method for setting a variable: Adding a logical AND to the value.

LED_GRN = (ivLEDGrnSequence & ivLEDSlot) && 1; 

I looked around a bit more for some of these occurrences and found them throughout the code, but in different forms:

As an argument for a function:

isoAgCmdHideShow(iObjectID,( (ecu.l & sVar->mask) && 1), (uint8_t *)TxMsg.buf); 

In a conditional:

if( (usbQueue.selection & USB_SELECTION_CAN_1) && 1 ) {return TRUE;} 

Does this extra logical AND actually change anything about the code, or is it just superfluous? I tried searching for this online, but the closest I found to an answer is Short-Circuit Evaluation which doesn't seem to apply in these situations because short-circuiting a 1 is useless.

In short, what does Logical AND 1 do for variable declaration?

 


This appears to be a trick to force any non-zero number to 1, while keeping zeros - alongside a more common !!(expr) idiomatic construct.

The idea is to set LED_GRN to 1 or 0 based on the value of ivLEDGrnSequence & ivLEDSlot.

Other ways to do the same thing are as follows:

LED_GRN = !!(ivLEDGrnSequence & ivLEDSlot); LED_GRN = (ivLEDGrnSequence & ivLEDSlot) != 0; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: