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.
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 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 3 years ago.
Improve this question
okay, so when i change the " = " in if( (i = 4) || (i = 5) ) to "==" it returns hello world. But when the "=" is kept at "=" the output is nothing. It does not give me a syntax error cuz ik you need to put "==" inside an if
void f( int i )
{
if( (i = 4) || (i = 5) ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So when the code is "if( (i = 4) || (i = 5) )" output is nothing (as in the screen is empty).
when the code is "if( (i == 4) || (i == 5) )" output is hello world.
my main question is: Why does == and = make a difference in the output but not give me a syntax error?
As #Carcigenicate said, == and = is different.
== is for comparing and = is for assigning.
An assignment a = b does not only set the value in variable a to b, but also returns the value of b. This way, an assignment like a = b = c is possible, because the value returned to be put in a is the same as has been set to b. You can use this trick in conditionals, as you've done, for example:
int x;
while(x = functionWhichCouldReturnZero()){
// Do something with x
}
When C++ tries to interpret the return value as a boolean (true or false), it interprets 0 as false, and all other values as true.
On the other hand, with (a == b), this is a pure conditional, and returns true if a is equal to b, otherwise it returns false.
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 debugging details. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
So, there are two dates and I have to check if date1 is further away than date2. What is the best way to do that?
int date1_day = 21, date1_month = 1, date1_year = 1990;
int date2_day = 19, date2_month = 5, date2_year = 1989;
if(???)
{
// date1 is further away
}
I'm struggling with this one for hours.
Try this without using any logical operators:
int date1 = date1_day + date1_month*100 + date1_year*10000;
int date2 = date2_day + date2_month*100 + date2_year*10000;
if(date1 > date2)
printf("date1 is further away than date2\n");
It's not rocket surgery:
if ( date1_year > date2_year ||
(date1_year == date2_year && date1_month > date2_month) ||
(date1_year == date2_year && date1_month == date2_month && date1_day > date2_day))
{
// date1 is further away
}
With a little more thought I'm sure you can come up with a simpler method.
COmpared to the 5 logical operators and 6 compares of Paul, R, here a version with 4 logical operators and 5 compares):
if(date1_year>date2_year ||
(date1_year==date2_year && (date1_month>date2_month
|| (date1_month==date2_month && date1_day>date2_day))))
You can use std::tie from <tuple> to lexicographically compare multiple variables.
if (std::tie(date1_year, date1_month, date1_day) >
std::tie(date2_year, date2_month, date2_day))
{
// date1 is further away
}
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 8 years ago.
Improve this question
What is the difference between this:
s = 0;
if (x > 0) s++;
if (y > 0) s++;
and this:
s = 0;
if (x > 0) s++;
else if (y > 0) s++;
Any help would be greatly appreciated.
When you write else if instead of if, program will not check the else if statement if x > 0, but when you write two if statements program will check both conditions, no matter if x > 0 or not.
In the first case the both conditions are checked because there are two different if statements.
In the second case the second condition is checked only if the first condition is evaluated to false.
Say x is 10 and y is 10. At the end of the first set of statements, s will be equal to 2. At the end of the second set of statements, s will be equal to 1.
The second example
s = 0;
if (x > 0) s++;
else if (y > 0) s++;`
will check for the y value only if x > 0 is false. The first example will execute the check regardless of x's value.