While loop with two true conditions but it only validate one [closed] - c#

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 5 years ago.
Improve this question
I need the code to run until both conditions at the while are true, I am using logical AND (&&):
while ((A.i != B.i) && (A.j != B.j))
{
// do something
}
at the run, the loop stops if
A.i=B.i
without checking the second condition, what am I doing wrong?

In a conditional statement where the && operator is used, the second condition is only evaluated if the first one is true. That is why when A.i==B.i you immediately break out of the check
"I need the code to run until both conditions at the while are true"
That confuses me, because if you want a while loop to run until certain conditions are true, then you would not want those conditions to be evaluated in the while() statement..
If you want your code to run UNTIL both of those conditions are true, then it really should be:
// Keep running while EITHER A.i is equal to B.i OR A.j is equal to B.j
while ((A.i == B.i) || (A.j == B.j))
{
// do something
}

Switch your && to ||
Your loop says "while A.i is not equal to B.i AND A.J is not equal to B.j" loop. Once A.i equal B.i that statement is no longer true, so the loop exits (it doesn't actually care about the second equality at that point). By using an OR it will loop until both conditions are false.

Not clear but I suspect this is what you are looking for
while ( !(A.i == B.i && A.j == B.j) )
Which is the same as
while ( A.i != B.i || A.j != B.j) )
I think?

OP, your question isn't very clear, but I'm pretty sure you are up against one of two problems.
This is a very common logic error
while (a == b) || (c == d)
is the same as
until (a != b) && (c != d)
Meanwhile,
while (a != b) && (c != d)
is the same as
until (a == b) || (c == d)
Notice how when you switch from == to !=, you also need to switch && for ||. A lot of devs miss this very obvious sort of logic flip (see De Morgan's Laws). Anyway, you just need to think the logic through. From your post, it is not clear what you are intending, but you might just need to switch && for ||.
Short circuit evaluation
Sounds like you wanted the second half of the logic to run, perhaps because the getter for j has some side effect that you want (which by the way isn't a great idea).
If you want the second half to always run, you should use | instead of ||. The || operator doesn't bother with the right hand side if the left hand side is true. Similarly, the && operator doesn't bother with the right hand side if the left hand side is false. This is called Short-circuit evaluation.

Because A.i != B.i evaluates to false so no need to complete the condition

Related

How does the order of expressions in an if block with && matter? [duplicate]

This question already has answers here:
Will an IF statement stop evaluating if it fails the first condition?
(8 answers)
Closed 5 years ago.
I have an if block being called in an update function of a game in C# unity 3D. Needless to say, it will be called a lot, so I'm trying to optimize as much as I can. I have two checks I need to make:
if (playerIsFlagged == true){
if (player.distance < 10){
doaction()
}
}
Now, for every update being called, I want to check the simple playerIsFlagged first, and then the distance. So I wrote:
if (playerIsFlagged == true && player.distance < 10){
doaction()
}
In this case, will the code always test both variable values before failing the if test, or when it checks that the first (playerisFlagged) is false it will automatically skip the second (distance) check?
In other words, is there a difference in performance in both cases?
In the first case, if playerIsFlagged is true, then it will check the second condition.
In the second case, if playerIsFlagged is false it will skip the second case. This is called short-circuit evaluation
First of all, if(booleanValue == true) is redundant, you can just write if(booleanValue) or if(!booleanValue) to check for false.
In response to your question, using double && means just that, check the first operando and if false ignore the rest. The same rule applies for double ||

Multiple Conditions in If Statement or Splitting

when i am using if statements with multiple conditions, how are they managed in the compiler?
A) Will it ignore the second Statement, if the first statement is not fulfilled or vice versa?
If(time > 3.0 && hitEnabled)
B) Late Defintions are often recommended, so should i prefere to use one condition in if statements?
if(time > 3.0)
if(hitEnabled)
Thanks!
if(time > 3.0 && hitEnabled)
In above statement hitEnabled will not be evaluated when time > 3.0 is false.
This is called short-circuit.
Following statement will evaluate hitEnabled even when time > 3.0 is false but returns true when both operands are true.
if(time > 3.0 & hitEnabled)//note bitwise &
if(time > 3.0)
if(hitEnabled)
Nested if statements are helpful when you need first condition to be checked many times etc.
if(time > 3.0 && hitEnabled)
{
//DoSomething1
}
if(time > 3.0 && flag)
{
//DoSomething2
}
This can be re written with nested if statements as follows
if(time > 3.0)
{
if(hitEnabled)
{
//DoSomething1
}
if(flag)
{
//DoSomething2
}
}
In this case I prefer nested if statement to avoid unnecessary checks
In case of an && if the first condition is false, the second condition will never be evaluated and the overall result is false. In case of an ||, if the first condition is true the second condition is not evaluated and the overall result is true. As Rob pointed out, it is known as short circuit evaluation.
This is useful in cases when we want to evaluate the second operand of the if statement only if the first operand returns true. For example, we may want to check for the validity of a variable before using it.
if(ptr != NULL && *ptr > x)
In this case the value of ptr will be checked against x only if it is not NULL.
A) It won't check hitEnabled if first condition will be false, if you want to do it you must use short-circuit AND (&) like below. Even if first condition will be False, it will check second one.
If(time > 3.0 & hitEnabled)
B) It strongly depends on what you want from you application and less on performance of your hardware. If you want to check both conditions in any case, B option is perfectly fine, but if you certain if you time > 3.0 is false and you don't want check second one, A option is preferable in my opinion. As I said before it is strongly depends on the logic of your program, so you can't get the right answer based on one line of code.
If you ask just about what better manner of writing without logic background, it's up to you. Both variants easy to read, if you follow code conventions.
The evaluation of the expression stops as soon as it is conclusively true or false.
This allows expressions like if (x != null && x.property ... as x.property will not be evaluated if x is null etc.
String someString = null;
if (someString != null && someString[4].Equals('a'))
{
//// not called
}
if (someString != null || someString[4].Equals('a'))
{
//// exception
}
Console.ReadLine();
In the first case:
If(time > 3.0 && hitEnabled)
If time > 3.0 is false then hitEnabled will never be checked. And it always starts checking conditions from left to right.
If you want to make sure that all conditions will be checked you should use || (logical OR) instead of && (logical AND) for example:
If(time > 3.0 || hitEnabled)
This:
if(time > 3.0 && hitEnabled)
equals
if(time > 3.0)
if(hitEnabled)
If the first condition is violated it wont check for the second one and it simply ignores.
If you want to put any code it is always better to make it nested.

Isn't there a way to "mouse over" a condition in an "if" statement to see true or false in VS2010?

While debugging, isn't there a way to "mouse over" a condition in an "if" statement to see if it evaluates to true or false in VS2010? I could have sworn there was, but I can't seem to get it to work.
Yes. Mouse-over the operator. For if(a || b), simply mouse-over the ||.
You can even break down complex expressions. For if(a || !(b is string)) you can mouse-over the !( portion to see what the result of the negation is.
Be sure you know your order of operations, though. For if(a || b && c), the || will give you the final result, where the && will give you the result of only the b && c portion.
Highlight the condition and type Ctrl-Alt-Q (quick watch).
Yes, if you select/highlight the expression, then hover over the selected text, it will show you the evaluation of whatever is selected.
As an option you can set your condition value to a bool variable and during debugging you can see it's value... Fore example:
bool condition = a > b;
if (condition)
{
// Do some stuff
}
And while debugging "mouse over" condition.

In C++ and C# are multiple condition checks performed in a predetermined or random sequence?

Situation: condition check in C++ or C# with many criteria:
if (condition1 && condition2 && condition3)
{
// Do something
}
I've always believed the sequence in which these checks are performed is not guaranteed. So it is not necessarily first condition1 then condition2 and only then condition3. I learned it in my times with C++. I think I was told that or read it somewhere.
Up until know I've always written secure code to account for possible null pointers in the following situation:
if ((object != null) && (object.SomeFunc() != value))
{
// A bad way of checking (or so I thought)
}
So I was writing:
if (object != null)
{
if (object.SomeFunc() != value)
{
// A much better and safer way
}
}
Because I was not sure the not-null check will run first and only then the instance method will be called to perform the second check.
Now our greatest community minds are telling me the sequence in which these checks are performed is guaranteed to run in the left-to-right order.
I'm very surprised. Is it really so for both C++ and C# languages?
Has anybody else heard the version I heard before now?
Short Answer is left to right with short-circuit evaluation. The order is predictable.
// perfectly legal and quite a standard way to express in C++/C#
if( x != null && x.Count > 0 ) ...
Some languages evaluate everything in the condition before branching (VB6 for example).
// will fail in VB6 if x is Nothing.
If x Is Not Nothing And x.Count > 0 Then ...
Ref: MSDN C# Operators and their order or precedence.
They are defined to be evaluated from left-to-right, and to stop evaluating when one of them evaluates to false. That's true in both C++ and C#.
I don't think there is or has been any other way. That would be like the compiler deciding to run statements out of order for no reason. :) Now, some languages (like VB.NET) have different logical operators for short-circuiting and not short-circuiting. But, the order is always well defined at compile time.
Here is the operator precedence from the C# language spec. From the spec ...
Except for the assignment operators,
all binary operators are
left-associative, meaning that
operations are performed from left to
right. For example, x + y + z is
evaluated as (x + y) + z.
They have to be performed from left to right. This allows short circuit evaluation to work.
See the Wikipedia article for more information.

Is this a reasonable use of the ternary operator? [closed]

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 9 years ago.
Improve this question
Are there any understanding / maintainability issues that result from code like
inVar1 == 0 ? NULL : v.push_back(inVar1);
inVar2 == 0 ? NULL : v.push_back(inVar2);
and so forth.
The possibly confusing idea is using the ternary operator for program flow rather than variable assignment, which is the usual explanation.
I haven't seen coding standards at work that address this usage, so while I'm comfortable doing this I'd like to find out if there is a good reason not to.
I think it's confusing and a lot harder to read than simply typing;
if (inVar != 0)
v.push_back(inVar);
I had to scan your example several times to figure out what the result would be with any certainty. I'd even prefer a single-line if() {} statement than your example - and I hate single-line if statements :)
The ternary operator is meant to return a value.
IMO, it should not mutate state, and the return value should be used.
In the other case, use if statements. If statements are meant to execute code blocs.
The ternary is a good thing, and I generally promote it's usage.
What you're doing here however tarnishes it's credibility. It's shorter, yes, but it's needlessly complicated.
I think this should be avoided. You could use a 1-line if statement in its place.
if(inVar1 != 0) v.push_back(inVar1);
Compilers these days will make an if as fast as a ternary operator.
You goal should be how easy is it for another software developer to read.
I vote for
if ( inVar != 0 )
{
v.push_back( inVar );
}
why the brackets...because one day you may want to put something else in there and the brackets are pre-done for you. Most editors these days will put them in anyway.
Your use of the ternary operator gains you nothing and you hurt the codes readability.
Since the ternary operator returns a value that you are not using it is odd code. The use of an if is much more clear in a case like yours.
As litb mentioned in the comments, this isn't valid C++. GCC, for example, will emit an error on this code:
error: `(&v)->std::vector<_Tp, _Alloc>::push_back [with _Tp = int, _Alloc =
std::allocator<int>](((const int&)((const int*)(&inVar1))))' has type `void'
and is not a throw-expression
However, that can be worked around by casting:
inVar1 == 0 ? (void)0 : v.push_back(inVar1);
inVar2 == 0 ? (void)0 : v.push_back(inVar2);
But at what cost? And for what purpose?
It's not like using the ternary operator here is any more concise than an if-statement in this situation:
inVar1 == 0 ? NULL : v.push_back(inVar1);
if(inVar1 != 0) v.push_back(inVar1);
While, in practice, I agree with the sentiments of those who discourage this type of writing (when reading, you have to do extra work to scan the expression for its side effects), I'd like to offer
!inVar1 ?: v.push_back(inVar1);
!inVar2 ?: v.push_back(inVar2);
...if you're going for obscure, that is. GCC allows x ?: y in place of x ? x : y. :-)
I use ternary operator when I need to call some function with conditional arguments - in this case it is better then if.
Compare:
printf("%s while executing SQL: %s",
is_sql_err() ? "Error" : "Warning", sql_msg());
with
if (is_sql_err())
printf("Error while executing SQL: %s", sql_msg());
else
printf("Warning while executing SQL: %s", sql_msg());
I find the former is more appealing. And it complies to DRY principle, unlike latter - you don't need to write two nearly identical lines.
I think you would be better served in doing a proper if structure. I even prefer to always have braces with my if structures, in the event I have to add lines later to the conditional execution.
if (inVar != 0) {
v.push_back(inVar);
}
I think that sometimes the ternary are a necessary evil in initializer lists for constructors. I use them mostly for constructors where I want to allocate memory and set some pointer to point at it before the body of the constructor.
An example, suppose you had an integer storage class that you wanted to have take a vector as an input but the internal representation is an array:
class foo
{
public:
foo(std::vector<int> input);
private:
int* array;
unsigned int size;
};
foo:foo(std::vector<int> input):size(input.size()), array( (input.size()==0)?
NULL : new int[input.size])
{
//code to copy elements and do other start up goes here
}
This is how I use the ternary operator. I don't think it is as confusing as some people do but I do think that one should limit how much they use it.
Most of the tortured ternaries (how's that for alliteration?) I see are merely attempts at putting logic that really belongs in an if statement in a place where an if statement doesn't belong or can't go.
For instance:
if (inVar1 != 0)
v.push_back(inVar1);
if (inVar2 != 0)
v.push_back(inVar2);
works assuming that v.push_back is void, but what if it's returning a value that needs to get passed to another function? In that case, it would have to look something like this:
SomeType st;
if (inVar1 != 0)
st = v.push_back(inVar1);
else if (inVar2 != 0)
st = v.push_back(inVar2);
SomeFunc(st);
But that's more to digest for such a simple piece of code. My solution: define another function.
SomeType GetST(V v, int inVar1, int inVar2){
if (inVar1 != 0)
return v.push_back(inVar1);
if (inVar2 != 0)
return v.push_back(inVar2);
}
//elsewhere
SomeFunc(GetST(V v, inVar1, inVar2));
At any rate, the point is this: if you have some logic that's too tortured for a ternary but will clutter up your code if it's put in an if statement, put it somewhere else!
inVar1 != 0 || v.push_back(inVar1);
inVar2 != 0 || v.push_back(inVar2);
common pattern found in languages like Perl.
If you have multiple method invocations in one or both of the tenary arguments then its wrong. All lines of code regardless of what statement should be short and simple, ideally not compounded.
A proper if statement is more readable, as others have mentioned. Also, when you're stepping through your code with a debugger, you won't be able to readily see which branch of an if is taken when everything is in one line or you're using a ternary expression:
if (cond) doIt();
cond ? noop() : doIt();
Whereas the following is much nicer to step through (whether you have the braces or not):
if (cond) {
doIt();
}
As mentioned, it's not shorter or clearer than a 1 line if statement. However, it's also no longer - and isn't really that hard to grok. If you know the ternary operator, it's pretty obvious what's happening.
After all, I don't think anyone would have a problem if it was being assigned to a variable (even if it was mutating state as well):
var2 = inVar1 == 0 ? NULL : v.push_back(inVar1);
The fact that the ternary operator always returns a value - IMO - is irrelevant. There's certainly no requirement that you use all return values...after all, an assignment returns a value.
That being said, I'd replace it with an if statement if I ran across it with a NULL branch.
But, if it replaced a 3 line if statement:
if (inVar == 0) {
v.doThingOne(1);
} else {
v.doThingTwo(2);
}
with:
invar1 == 0 ? v.doThingOne(1) : v.doThingTwo(2);
I might leave it...depending on my mood. ;)

Categories