Confused about if condition CPP - c++

Confused about if condition, how does it executes following statements.
if(1 && (1 || 0) != 0) or if(1 || (1 && 0) != 0)
In above if statement what is the sequence of executing/validating the statements.
(left to right or right to left) if left to right, then if first argument/expression is true does it evaluates 2nd expression/argument? is it true for both the logical AND and OR operators.
Thanks.

Logical && short circuits if the first operand evaluates to false (because false && x is false for all x)
Logical || short circuits if the first operand evaluates to true (because true || x is true for all x)
They both evaluate left-to-right.

It's left to right
First executes 1. Then executes (1 || 0) != 0. To do that it executes 1 || 0 -> true, so the whole thing is true.
First executes 1 - it's true, so it short circuits and returns true.

It's left to right. || short-circuits if first expression is true, && if first expression is false.

Both things are fundamentally different go read D Morgans Laws!s

lets break it down step-by-step:
(1 || 0) becomes true as 1 short-circuits the expression
so (1 || 0) != 0 is true
1 && true is true by the definition of the logical && operator
or is a define/keyword for || but the first section is already true, so we short-circuit the expression again and the code inside the if block is executed.

Related

Why does (0 && 1 == 0) not evaluate to true?

In my if statement, the first condition for && is 0 (false), so the expression 0 && (a++) is equal to 0, right? Then 0==0 it should be true. Why am I getting else here? Please explain!
int a=0;
if(0 && (a++)==0)
{
printf("Inside if");
}
else
{
printf("Else");
}
printf("%i",a);
The == operator has a higher priority than the && operator, so this line:
if(0 && (a++)==0)
is treated like this:
if( 0 && ((a++)==0) )
So the whole expression under the if is false, and a++ is not even evaluated due to short circuitry of the && operator.
You can read about Operator Precedence and Associativity on cppreference.com.
When in doubt, you should use parenthesis to express your intention clearly. In this case, it should be:
if( (0 && (a++)) == 0 )
Though, it does not make any sense, as it always evaluates to true and a++ is not incremented here, either.
As already mentioned, the precedence of == is higher than precedence of &&, so the statement is resolved into
if( 0 && ((a++)==0))
However, still even if you add the correct order of brackets, a++ returns the original value of a, which is 0, but the a is incremented. If you want to return the updated value of a, you should write ++a
if( ((++a) && 0) == 0 )
Although the question seems easy it's very error-prone.
We need to know the precedence of various operators involved in this.
1. postfix (++)
2. ==
3. Logical AND (&&)
the final expression can be seen as: if ( (0 && (a++)) == 0 )
which is true. Hence statement under if is evaluated to be true.

C++ comma operator confusion

Similar question to:
How is the comma operator being used here?
BOOL bShowLoadingIcon = FALSE;
if (sCurrentLevelId_5C3030 == 0 || sCurrentLevelId_5C3030 == 16 || (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1))
{
bShowLoadingIcon = FALSE;
}
In the above code sample what values/range of sCurrentLevelId_5C3030 would cause bShowLoadingIcon to be set to TRUE. Is it possible it would be set to TRUE and also become true (overall if expression) thus also then being set back to FALSE?
I have no idea what (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1) is actually doing.
C++ only evaluates a boolean OR if it needs to. So if sCurrentLevelId_5C30303 is 0 or 16, the last statement never gets evaluated.
If (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1) does get evaluated, it first sets bShowLoadingIcon to TRUE and then evaluates to the result of sCurrentLevelId_5C3030 == -1. If that's true, then bShowLoadingIcon will just get set back to FALSE.
So in summary, bShowLoadingIcon is set to FALSE. Then if sCurrentLevelId_5C3030 is neither 0 nor 16, then bShowLoadingIcon is set to TRUE, only to be set back to false if sCurrentLevelId_5C3030 is -1.
So, in even more summary, bShowLoadingIcon is set to TRUE if sCurrentLevelId_5C3030 is neither 0 nor 16 and stays that way so long as sCurrentLevelId_5C303030 is not -1.
It's equivalent to:
BOOL bShowLoadingIcon = (
(sCurrentLevelId_5C3030 != 0) &&
(sCurrentLevelId_5C3030 != 16) &&
(sCurrentLevelId_5C3030 != -1)) ? TRUE : FALSE:
Or, if you prefer:
BOOL bShowLoadingIcon = (
(sCurrentLevelId_5C3030 == 0) ||
(sCurrentLevelId_5C3030 == 16) ||
(sCurrentLevelId_5C3030 == -1)) ? FALSE : TRUE;
In C++, the comma operator (statementX, statementY) first executes statementX, and then statementY. The expression holds the value of the second statement.
In your code, bShowLoadingIcon is assigned the value TRUE, and then the value that C++ checks for in the if statement is whether sCurrentLevelId_5C3030 == -1.

C++, Enum and OR condition

I have an enum with 3 values:
enum InputState { Pressed, Released, Held };
And I'm using it in this code:
//GetState returns an InputState
if(myInput.GetState(keyCode) == InputState::Pressed)
{
//This means "keyCode" has the state "Pressed"
}
Why doesn't this work?
if(myInput.GetState(keyCode) == (InputState::Pressed || InputState::Held))
{
//This is always false
}
if((myInput.GetState(keyCode) == InputState::Pressed) || (myInput.GetState(keyCode) == InputState::Held))
{
//This works as intended, triggers when "keyCode" is either Pressed OR Held
}
As a test, I did:
//Using the same values from the enum, but as int now
if(1 == (1 || 2))
{
//This works as intended
}
Am I missing something?
|| is a binary operation that expects two boolean values. In your example, the boolean values are the result of testing for equality with ==.
To see why your simplified example works, let's evaluate the expression
1 == (1 || 2)
We must start inside the parentheses first, so we are going to first evaluate (1 || 2). In C++, any non-zero value is equivalent to true when it is used in a boolean expression, so (1 || 2) is equivalent to (true || true) which evaluates to true. So now our expression is
1 == true
Again, 1 is equivalent to true in this context, so this comparison is the same as true == true, which of course evaluates to true.
Yes, you are missing something. This worked by total accident:
(1 == (1 || 2))
It is NOT set comparison. It simply calculated (1 || 2) as true, then converted true to its integral value (1).
The same thing would have happened with
(1 == (1 || 4))
(1 == (0 || 1))
(1 == (0 || 4))
and they all are true.
But
(2 == (1 || 2))
is false.

How do C++ operators work

Given that x = 2, y = 1, and z = 0, what will the following statement display?
printf("answer = %d\n", (x || !y && z));
It was on a quiz and I got it wrong, I don't remember my professor covering this, someone enlighten me please... I know the answer I get is 1, but why?
The expression is interpreted as x || (!y &&z)(check out the precedence of the operators ||, ! and &&.
|| is a short-circuiting operator. If the left operand is true (in case of ||) the right side operand need not be evaluated.
In your case x is true, so being a boolean expression the result would be 1.
EDIT.
The order of evaluation of && and || is guaranteed to be from left to right.
If I'm not mistaken, it will print 1. (Let's assume short circuiting is off)
(x || !y && z) or (true || !true && false) will first evaluate the ! operator giving (true || false && false)
Then the &&: (true || false)
Then || : true
Printf will interpret true in decimal as 1. So it will print answer = 1\n
Given that x = 2, y = 1, and z = 0,
what will the following statement
display?
printf("answer = %d\n", (x || !y && z));
Ok - feeling a bit guilty for the harsh quip re poor wording of the question, so I'll try to help you in a different way to the other answers... :-)
When you've a question like this, break it down into manageable chunks.
Try:
int x = 2, y = 1, z = 0;
printf("true == %d\n", 10 > 2); // prints "1"
printf("false == %d\n", 1 == 2); // prints "0"
printf("!y == %d\n", !y); // prints "0"
printf("(x || !y) == %d\n", x || !y); // "1" - SEE COMMENTS BELOW
printf("(!y || z) == %d\n", !y || z); // "0"
printf("(x || !y && z) == %d\n", x || !y && z); // "1"
In the output there, you've got everything you need to deduce what's happening:
true == 1 reveals how C/C++ convert truthful boolean expressions to the integral value 1 for printf, irrespective of the values appearing in the boolean expression
false == 0 reveals how C/C++ converts false expressions to "0"
(!y) == 0 because ! is the logical not operator, and C/C++ consider 0 to be the only integral value corresponding to false, while all others are true, so !1 == !true == false == 0
(x || !y) == 1, and you know !y is 0, so substituting known values and simplifying: (2 || 0) == 1 is equivalent to (true or false) == true... that's understandable as a logical rule
(!y || z) == 0 - substituting known values: (0 || 0) == (false or false) == false == 0
(x || !y && z) == 1: here's the crunch! From above, we know:
x || !y is 1/true, which if relevant would imply 1/true && z/0/false == 1/true <- this clearly doesn't make any sense, so it must not be the way C/C++ are calculating the answer!
(!y && z) is false, which if relevant would imply x/2/true || false == 1/true <- this is true, so it must be the implicit order.
In this way, we've derived the operator precedence - the order of evaluation of the || and && operators, from the results that the compiler is displaying, and seen that if and only if && is valuated before || then we can make some sense of the results.
answer = 1
or maybe:
answer = -27
2 || !1 && 0
2 || 0 && 0
2 || 0
true
true = non-zero value
printf("answer = %d",*true*); -> who knows
Most compilers will output answer = 1. I wouldn't confidently state that all compilers will do that though, but I am confident all compilers would return non-zero.
I'm not going to give you the outright answer because you could just compile it and run it, but the question is just testing to see if you know operator precedence.

what is the difference in using && and || in the do...while loop?

#include<iostream>
using namespace std;
int main()
{
char again;
do
{
cout<<"you are in the while loop";
cout<<"do you want to continue looping?";
cin>>again;
} while (again != 'n' || again != 'N');
system("pause");
return 0;
}
i know something is wrong with the test condition in the 'while'. But I can't figure it out.
when the input of the user is neither 'n' nor 'N', the loop should keep on printing the code "you are in the while loop". Once 'n' or 'N' is pressed, the program will be terminated.
However for my code, program will keep on looping the code regardless what character i enter.
But when i change the '||' to '&&', the program can ran as desired.
Anyone can tell me what is going on?
This is a common boolean logic question. || means "or," which means "as long as one side of this is true, then the expression is true." So when you pass an uppercase 'N' to c != 'n' || c != 'N' the program says "well, 'N' is not equal to 'n', therefore one side of the expression is true, therefore the whole expression is true and there is no need to check the rest of the expression." Even when you press lowercase 'n', the program says "well, 'n' is equal to 'n', but it's not equal to 'N', therefore one side of the expression is true, therefore the whole expression is true." This is what is happening in your while loop.
On the other hand, && means "and" which means "both sides of the expression must be true"; when you pass an uppercase 'N' to c != 'n' && c != 'N' the program thinks "'N' is not equal to 'n', but it is equal to 'N', therefore only one side of the expression is true, therefore the expression is false."
This gets confusing because if you were testing to see if the characters entered were equal to particular values you would use || (e.g., "I want to know if 'a' or 'b' or 'c' was entered").
Basically, when you would use || for a particular expression, and you want the opposite of that expression then you need to change to && (e.g., I want none of 'a', 'b' or 'c'; or to put it another way, the value cannot be 'a' and it cannot be 'b', and it cannot be 'c'"). Likewise, if you would use && for a particular expression, and you want the opposite of that expression then you need to use ||. This is one of De Morgan's laws, which I would recommend you read up on so you can avoid having to rediscover each of them on your own.
Yes: || is "or" and && is "and".
Every character is either "not 'n'" or "not 'N'" because it can't possibly be both 'n' and 'N' simultaneously.
Another (probably simpler to read) way of writing the condition would be:
!(again == 'n' || again == 'N')
which means "the opposite of (again is either 'n' or 'N')".
It is the boolean algebra called "De Morgan's laws".
Not (P And Q) = (Not P) Or (Not Q)
Not (P Or Q) = (Not P) And (Not Q)
In your case, you want users not to enter 'n' or 'N', it can be translate in to this logic.
!(again == 'n' || again == 'N')
When applying De Morgan's laws, it will be
(again != 'n' && again != 'N')
For more info, you might want to read Propositional logic
Although the original poster is happy now, I didn't see this in the other answers:
(true && true ) == true
(true && false) == false
(false && true ) == false
(false && false) == false
(true || true ) == true
(true || false) == true
(false || true ) == true
(false || false) == false
!true == false
!false == true
That's everything!
I understand your problem well,and here is the explanation:
The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again. If the test condition is FALSE, the loop terminates and program execution continues with the statement following the while.
in your code,when you press'n' or'N',your test condition will be always one true and one false,
so when you use || you will satisfy the test condition (true||false=true) ,so the program will execute the body of the loop again.
but when you use && ,this will gives (true && false =false),the test condition is not statisfied anymore,so the program will not execute the body of the loop again.
I hope that's helpful.....enjoy programing!
Ameraradi
&& is a logical AND.
|| is a logical OR.
(also, & is a bitwise AND, and | is a bitwise OR.)
you might want to try while(!(again == 'n' || again == 'N'))