Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm having an issue with boolean and logical operators. I'm trying to get wantsToppings to evaluate to true if toppings equals 'T' or 't', but this code evaluates to true, regardless of user input. I'm not sure what I am missing, but I know I gotta be missing something.
Thanks for any help.
cout << "Toppings wanted (T for toppings/N for no toppings)? ";
cin >> toppings;
if (toppings == 't' || 'T'){
wantsToppings = true;
} else {
wantsToppings = false;
}
You are missing how logical operators work. Here is what you do:
if (toppings =='t' || 'T')
and here is how it's done:
if (toppings =='t' || toppings == 'T')
You don't really need the complexity of the if either, it could just be:
wantsToppings = (toppings == 't' || toppings == 'T');
The expression
if (toppings == 't' || 'T')
does not mean to toppings is either of 't' or 'T', but rather essentially (it's in fact a little bit more complicated than this once you factor in lazy evaluation):
evaluates each sub-expression (the expression toppings == 't' and the expression 'T')
convert results of those expressions to boolean values if required
perform the logical or (||) of the above boolean values
Now 'T' is a char which gets promoted to the boolean value true, hence the result is always true.
As others have pointed out, the expression you are looking for is
if (toppings == 't' || toppings == 'T')
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Any ideas, or tips (links to tutorials), are much appreciated, I'd be happy to take a reference if this has been addressed elsewhere.
I haven't been able to find anything referencing how to use the OR on three operands here is the question that I got wrong.
Let A = true, B = false, and C = true. Evaluate the following:
(3 != 5) && !(A || B || C)
Response: True
Score: 0 out of 1 No
Is this a trick question?
Firstly, evaluate the lefthand operand of (3 != 5) && !(A || B || C).
It is 3 != 5, which is true.
Then, evaluate the righthand operand of (3 != 5) && !(A || B || C).
It is !(A || B || C).
To evaluate this, let's evaluate the operand of ! operator, which is A || B || C.
|| operator has left-to-right assosiativity, so A || B || C is treated as (A || B) || C.
Now A is true, so A || B is true without seeing the value of B. You can say that A || B || C is true from this.
A || B || C is true, so !(A || B || C) is false. Therefore the original expression (3 != 5) && !(A || B || C) is false.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In code I come to situation like this:
if (a && b || c && d || e && f || g && h){
// do something
}
Like this:
if len(env.workers) == 0 && env.minQueue.Len() == 0 || len(env.workers) == len(env.daemonList) && env.minQueue.Len() == 0 || len(env.workers) > 0 && len(env.workers) == len(env.daemonList) {
env.shouldStop = true
return nil
}
But it's hard to debug and find errors. Is there any way to use more friendly constructuion to replace such statement.
As #Eugene mentioned it's always good idea to break long expressions like this into multiple smaller expressions.
exp1 = a && b
exp2 = c && d
exp3 = exp1 || exp2
exp4 = e && f
exp5 = g && h
exp6 = exp4 || exp5
exp7 = exp3 || exp6
if(exp7){
//doSomething
}
This may look absurd in beginning but believe me it has long way to go, at any point you can come back to the above code and easily understand what's cooking there. In fact if you like using debuggers then doing this would make your life way easier.
Also in point of performance, all you are doing is making extra 7 boolean variables. It's insignificant when code readability is concerned. And the thumb rule for better code readability is naming your variable right, not exp1,2,....
You use len(env.daemonList), len(env.workers) and env.minQueue.Len() multiple times. Storing them in variables not only shortens up that long condition, but also gives you variables that can be referenced when debugging.
You could write it as:
w_len = len(env.workers)
d_len = len(env.daemonList)
q_len = env.minQueue.Len()
if w_len == 0 && q_len == 0 || w_len == d_len && q_len == 0 || w_len > 0 && w_len == d_len {...
Now, of course the problem here is that while shorter, the names aren't as descriptive. You could give them better names at the cost of verbosity. How much you want to lean in each direction is a matter of taste and context.
This also doesn't "get rid" of the if like the title states, but that's not always a great goal to have. ifs aren't necessarily bad.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I'm staring at the following expression, written by someone else:
if (variableA == CaseA && GetCase(variableB) == CaseA && GetCase(variableC) == CaseA && !CaseB(variableB) || variableA != CaseA)
{
// do stuff
}
What's really tripping me up is this bit:
!CaseB(variableB) || variableA != CaseA
Because there aren't any parentheses to group the conditionals together.
How will the C++ compiler evaluate these if statements? If one of the AND operators evaluates to false, does this mean that the OR won't be checked due to short circuit?
Edit
Wow, I guess the haters really want to hate today, considering the amount of downvotes for each answer in addition to the -4 (and counting?) for the question. And, uh, no actual explanation for why? Lol.
Stay classy, people. Stay classy. ;)
For the record, simply stating that there's a "left to right evaluation" doesn't really say much in terms of providing a valid answer for the question. I actually did use the great power of Google (which also lead to a few posts here that I read) before posting.
I'll admit my mistake here was failing to mention that, and while I think that the C++ reference is the most natural link to post as a supplement for an answer, the best information I was able to get was inadvertently from here, via the following quote in a source code example:
|| has lower precedence than &&
Which is arguably vague, because "lower precedence" isn't actually specified in terms of what that means in this context.
Either way, to those who actually contributed you will receive an upvote - I'm going to accept the answer which gave me what I was really looking for.
The expression is equivalent to:
( (variableA == CaseA) &&
(GetCase(variableB) == CaseA) &&
(GetCase(variableC) == CaseA) &&
(!CaseB(variableB))
)
||
(variableA != CaseA)
The expression will be evaluated from the top down (because of the short circuit rules), and if any of the first four lines return false, none of the remain first four lines will be evaluated. If (and only if) one of the first four lines return false, then the final line will be evaluated.
But I am interested that the last line is the negation of the first
Operator && has higher precedence than operator || as seen here so all of the && will occur first, then lastly the ||, in other words if I added parentheses
if ((variableA == CaseA && GetCase(variableB) == CaseA && GetCase(variableC) == CaseA && !CaseB(variableB)) || variableA != CaseA)
So basically
if (all_the_ands || variableA != CaseA)
If the left hand side of that expression is true, the right hand side will not execute due to short circuiting.
http://en.cppreference.com/w/cpp/language/operator_precedence
The precedence is as listed in the answer by Sachin Goyal (and as listed more clearly in the above link).
The specific precedence detail that seems to be confusing you is that the ! associates directly to CaseB(variableB) not to anything larger.
The sequence is left to right across each && or || with short circuiting.
If the expression to the left of the !CaseB(variableB) || variableA != CaseA you asked about is false then the !CaseB(variableB) is skipped and it evaluates variableA != CaseA. But if the earlier expression is true, it uses the value of !CaseB(variableB) to decide whether to evaluate the rest.
The combination of initial test variableA == CaseA with final test variableA != CaseA seems confused. It might mean what was intended, but could have been done more simply.
When you code (X && Y && Z) the meaning is ((X && Y) && Z) but because of the way && acts, that is the same as (X && (Y && Z)). So variableA == CaseA acts like a guard on the rest of the operands of the &&s, so that when that is false you skip all the way to the other side of the || and make the opposite test and end up resolving true. So it would have been simpler to get the same effect by just starting with variableA != CaseA ||
In your example , operator precedence is as below .
! > == > && > ||
So , first statement evaluated would be
1) !CaseB(variableB) only if all other "&&" condition happens to be true .If any of "variableA == CaseA && GetCase(variableB) == CaseA && GetCase(variableC) == CaseA " is false then short circuting will happen here and "!CaseB(variableB)" won't be executed .
After that ,
2) if condition 1) is true , again short circuiting( as you have correctly guessed ) else "||" condition will be evaluated .
You are right , if condition 2) happens to be true , other or(||) condition won't even be checked due to short circuit .
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to find out whether a string has words in it
if( mystring[i] == 'a' | 'b' | 'c' | 'd' | 'e' |)
// do stuff but it always does stuff no matter that mystring[i] is.
is always evaluating to true even if mystring[i] = a space or a period
I tried to use strcmp but I couldn't get that working right. I want it to evaluate true
only if it = a letter.
You cannot compare multiple values like that. Use a switch statement instead:
switch( mystring[i] )
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
{
// do something
break;
}
default:
{
// do something else
break;
}
}
In C/C++, if a case block does not have a break then its execution will continue in the next case block. Thus, all 5 values will execute the same // do something code. Some languages do not do that.
Another option, only because your values are consecutive, is to use this:
char ch = mystring[i];
if( (ch >= 'a') && (ch <= 'e') )
{
// do something
}
else
{
// do something else
}
There are two issues in your code. First, due to precedence, your expression is being evaluated as:
(mystring[i] == 'a') | ('b') | ('c') | ('d') | ('e')
Second you are using bitwise-or instead of logical-or. What you want to do is have a full condition as each term and switch to logical or:
char c = mystring[i];
if (c == 'a' || c == 'b' || c == 'c' ...)
Finally, if you are planning to check for every lower case letter, the standard library has an islower method which can check that:
if (islower(mystring[i])
#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'))