Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Logical AND 1 when setting a variable in C

Tags:

c

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?

like image 531
StephenKercher Avatar asked Jun 29 '18 18:06

StephenKercher


People also ask

What is the meaning of & and && in C programming?

& 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 && .

How does && operator work in C?

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.

How do you assign a boolean to a variable in C?

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.

Is 1 true or false in C?

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.


2 Answers

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;
like image 152
Sergey Kalinichenko Avatar answered Oct 14 '22 07:10

Sergey Kalinichenko


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.

like image 24
Govind Parmar Avatar answered Oct 14 '22 06:10

Govind Parmar