Hey i am working on a code and i stuck inside this if condition which is
(Not a actual Code simplified for better understanding)
if(18&2==2)
do something;
this if condition not executing but if i write like this
if(18|2==18)
do something;
it executed normal
also when I,
printf("%d",18&2);
it gives 2 now i am so confused why the above if statement not executing,
is it because of precedence ,please explain thanks.
Yours is a precedence "error". The bit-wise operators have lower precedence than equality. Making 18 & 2 == 2 into 18 & (2 == 2), which is 18 & 1. That last one obviously evaluates to 0, since 18 is divisible by 2.
In such cases, when you get "weird results". Start by adding parenthesis to make sure every operator operates on the operand you expect it too.
The precedence of == is higher than &.
The expression:
if(18&2==2)
evaluated as follow:
2==2 result in logical true (1).
18&1 result in logical false (0);
Hence the if condition (18&2==2) evaluated as false.
Related
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;
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.
It's converting the result of the bitwise AND to either 0 or 1. The result of the bitwise AND can be 0 or any non-zero number. But after the logical AND, the result can only be 0 or 1.
So the first two examples may be useful. The third example with the if statement is definitely not useful, since if converts the expression to a boolean.
The result of logical operation (in this case &&) is either 0 or 1. The result of arithmetic or bitwise operation (& in this case) is 0 or non-0. If we want to convert any non-0 to 1 we perform a logical operation on it. The more common and idiomatic way to accomplish this is the double negation:
LED_GRN = !!(ivLEDGrnSequence & ivLEDSlot);
int j=4;
(!j!=1)?printf("Welcome"):printf("Bye");
In the above code segment, according to me, first j!=1 will result in true and !true is false which must result in printing Bye but I get Welcome as the output.
Can anyone explain this one?
! executed first because unary operator ! has a higher precedence than !=.
!4 become 0 then 0 != 1 become true.
So, output is Welcome.
!j!=1 is (!j)!=1, not !(j!=1).
This is because ! (NOT) has higher operator precedence than != so...
j = 4; // 4
!j // 0
In your condition, 0 != 1 will be true so "Welcome" is printed.
For your desired outcome, your condition would have to be !(j!=1).
The Logical NOT operator ! has a higher precedence than the Not Equal To operator !=
So your condition is equivalent to ((!j) != 1)
See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
The unary operator '!' has a higher precedence than '!='.
Read - https://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm.
Hey thank you very much for your time! I'm having trouble understanding the syntax of a statement in my audio coding textbook. In one example there is a print function that goes like this
printf("%d semitones up or %d semitones down\n", interval,
interval ? 12-interval : 0 );
The part I don't understand is the conditional operator, or "?". It seems like I should just read it as "if interval does not equal 0, interval = 12 - interval" but the syntax here seems strange. I'm used to the conditional operator being a more fleshed out statement, like:
a = b > c ? b : c;
"If b is bigger than c, than a = b; else a = c"
Could someone point me to any other reference for this, or explain more about this syntax? I can't find similar examples.
You're almost right, but there's no assignment taking place. It's saying "if interval is non-zero, pass 12 - interval to the printf statement, otherwise pass 0".
In general the ternary operator looks like this:
a ? b : c
Where a, b, and c are all expressions. If a evaluates to non-zero, the ternary operator evaluates as if it were b, and if a evaluates to zero, the ternary operator's result is the result of evaluating c.
Your second example is a combination of the ternary operator and the assignment operator. The ternary operator itself doesn't perform any assignments.
Any expression that results in a boolean will do. In the case of C, where integers can be used as booleans, the value 0 is considered false and anything else is considered true.
So, in your case, interval ? 12-interval : 0, means: if interval is nonzero, use 12-interval, otherwise, use 0. To be extra verbose, you could rewrite it to:
interval != 0 ? 12-interval : 0
Consider this code:
int a = 5;
if (a == 5 || a == 10)
doSomething();
In this case a is 5 so the first condition is true. Will the program check if the second condition is true or it will start executing doSomething() immediately after it makes sure that a is really 5?
It will start executing immediately. This is known as short-circuit evaluation.
http://en.wikipedia.org/wiki/Short-circuit_evaluation
The second condition won't be checked. C short-circuits logical evaluations, so as soon as the truth or falsehood of the condition can be determined it stops.
Note that given the code as posted, the compiler might not even generate code to perform the first comparison as it can determine at compile time that the condition is satisfied and no intervening code could alter the value of a.
Share and enjoy.
int a = 5;
if (a == 5 || a == 10)
doSomething();
in this example the left operand operand of || is evaluated to 1 so the right operand will not evaluated.
The compiler is required to not evaluate the right operand of || operator when the left operand is evaluated to 1.
When it comes to the logical operations, the compiler will stop evaluating the expression as soon as its finds the truth or falsehood of the expression.
The truth-table for logical or (||) operation is as follows:
A B A||B A&&B
0 0 0 0
0 1 1 0
1 0 1 0
1 1 1 1
So for an expression like a == 5 || a == 10, when a is equal to 5, the expression will be evaluated to true when the compiler sees a == 5 part. So irrespective of whether the rest of the expression is evaluated to true or false, due to the logical or (||) operator (refer the above truth-table), this expression will be evaluated to true. So the compiler will discard executing the rest of the expression.
Any decent compiler will not even check the first condition since at compile time it knows at once that it should invoke your method. (but of course all comments about short circuit hold true - but not here ;-)
Here is a c program.I am getting a strange output.
When num1=10 and num2=20->
#include<stdio.h>
void main()
{
int num1=10,num2=20;
clrscr();
if(num1,num2)
{
printf("TRUE");
}
else
{
printf("FALSE");
}
getch();
}
Output:
TRUE
when num1=0 and num2=220
Output:
TRUE
But when num1=0 and num2=0:
Output:
FALSE
Why does this happen?
also,what does this given below code mean:
if(num1,num2)
Thanks in advance!
You're using the comma operator. That operator first evaluates its first operand, then drops the result on the floor and proceeds to evaluate and return its second operand.
That's why your program only prints FALSE if num2 evaluates to false in a boolean context (like e.g. 0, 0.0 or NULL).
In:
if(num1,num2)
the last expression overrides all preceeding ones so it's the same as:
if(num2)
since, num2 is 0, you get FALSE.
If you check this out,
http://msdn.microsoft.com/en-us/library/2bxt6kc4(v=vs.71).aspx
the , stands for sequential evaluation, meaning the expressions are evaluated one after another, the last being your num2.
Learn about comma operator in c http://en.wikipedia.org/wiki/Comma_operator.
i=(a,b) means store b in i.
Everything else than 0 in c is true.
so if(3) if (-3) all are true
only if(0) is false
if(num1,num2)
Is a use of the comma operator. The Comma operator calculates the first operand and discards the result then the second operand and returns the result. Thus (a, b) calculates a, calculates b and then returns b.
This should clear up your confusion for the logical cases, in each of them the statement has the effect of looking at the value of b.
if(num1,num2)
is not a syntax error, but it is a logic error. Basically, this will resolve to being only
if(num2)
Only the last variable is evaluated.
I assume what you want is 'if a and b are true'. The comma like you are using means to evaluate just the last variable.
What I think you want is:
if(num1 && num2) /* num1 AND num2 */
You need to use && (logical AND) not a single & (Which is bitwise AND)