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?
& is bitwise operator and, && is logical for example if you use two number and you want to use bitwise operator you can write & . if you want to use to phrase and you want to treat them logically you can use && .
The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical AND has left-to-right associativity.
You would need to #include <stdbool. h> to use booleans, but in C we usually use an integer. The way it works is 0 is false, anything else is true.
C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.
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;
Doing x && 1
produces either 1 or 0, regardless of what non-zero value the left operand evaluates to.
From the C standard:
§6.5.13 Logical AND operator
The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With