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.
Related
Which of the following is preferable when checking two possible outcome to condition?
This one:
if (x == 2) {
}
else if (x != 2){
}
Or that one
if (x == 2) {
}
if (x != 2){
}
When you use sequential if-statements, then all conditions get evaluated.
When you use else if, the first matching conditional body (including the first if) is entered, but all conditions up to that point will still be evaluated from top-to-bottom.
When you have conditions that only can have two cases, then you don't need else if , and can just use else
In the first snippet the else if ( x != 2 ) that is the opposite is useless because the previous condition failed thus it is always true, therefore only else is needed.
For the same reason exposed above, the second version is a code smell because you check two times the value : you should only use this if you modify x in the previous test block otherwise it is a defect, or at least an opinion and a matter of preference that reduces the speed due to more IL opcodes, and therefore more machine code, and therefore more CPU ticks that is ~x2 on the condition line.
C# - Decision Making
Boolean Algebra for Dummies
What is Boolean Logic?
Boolean logic
Boolean Logic
Boolean algebra
Why do you need second check? Just use else statement after first if statement.
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
In a complex object like OperationContext is it safe to write such code:
if(OperationContext.Current!=null &&
OperationContext.Current.ServiceSecurityContext !=null &&
OperationContext.Current.ServiceSecurityContext.WindowsIdentity !=null)
Or do I need to separate the code to three if statements?
My question is if the OperationContext.Current is null I afraid that OperationContext.Current.ServiceSecurityContext will throw a NullReferenceException.
The && operator in C# uses short circuit evalulation so your code is fine.
What this means is the left-hand side of the condition is evaluated first and if it passes the right-hand side is then evaluated.
It is safe. Right side of && is evaluated only if left side is true.
Here is the MSDN explanation:
The operation
x && y
corresponds to the operation
x & y
except that if x is false, y is not evaluated, because the result of
the AND operation is false no matter what the value of y is. This is
known as "short-circuit" evaluation.
It won't, please take a look at the definition of the && operator: http://msdn.microsoft.com/en-us/library/2a723cdk.aspx. If the first part is false, the second one is simply not evaluated.
Your code would throw that exception if you used the & operator.
Assume myObj is null. Is it safe to write this?
if(myObj != null && myObj.SomeString != null)
I know some languages won't execute the second expression because the && evaluates to false before the second part is executed.
Yes. In C# && and || are short-circuiting and thus evaluates the right side only if the left side doesn't already determine the result. The operators & and | on the other hand don't short-circuit and always evaluate both sides.
The spec says:
The && and || operators are called the conditional logical operators. They are also called the “shortcircuiting” logical operators.
...
The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true
...
The operation x && y is evaluated as (bool)x ? (bool)y : false. In other words, x is first evaluated and converted to type bool. Then, if x is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.
(C# Language Specification Version 4.0 - 7.12 Conditional logical operators)
One interesting property of && and || is that they are short circuiting even if they don't operate on bools, but types where the user overloaded the operators & or | together with the true and false operator.
The operation x && y is evaluated as T.false((T)x) ? (T)x : T.&((T)x, y), where
T.false((T)x) is an invocation of the operator false declared in T, and T.&((T)x, y) is an invocation of the selected operator &. In addition, the value (T)x shall only be evaluated once.
In other words, x is first evaluated and converted to type T and operator false is invoked on the result to determine if x is definitely false.
Then, if x is definitely false, the result of the operation is the value previously computed for x converted to type T.
Otherwise, y is evaluated, and the selected operator & is invoked on the value previously computed for x converted to type T and the value computed for y to produce the result of the operation.
(C# Language Specification Version 4.0 - 7.12.2 User-defined conditional logical operators)
Yes, C# uses logical short-circuiting.
Note that although C# (and some other .NET languages) behave this way, it is a property of the language, not the CLR.
I know I'm late to the party, but in C# 6.0 you can do this too:
if(myObj?.SomeString != null)
Which is the same thing as above.
Also see:
What does question mark and dot operator ?. mean in C# 6.0?
Your code is safe - && and || are both short-circuited. You can use non-short-circuited operators & or |, which evaluate both ends, but I really don't see that in much production code.
sure, it's safe on C#, if the first operand is false then the second is never evaluated.
It is perfectly safe. C# is one of those languages.
In C#, && and || are short-circuited, meaning that the first condition is evaluated and the rest is ignored if the answer is determined.
In VB.NET, AndAlso and OrElse are also short-circuited.
In javaScript, && and || are short-circuited too.
I mention VB.NET to show that the ugly red-headed step-child of .net also has cool stuff too, sometimes.
I mention javaScript, because if you are doing web development then you probably might also use javaScript.
Yes, C# and most languages compute the if sentences from left to right.
VB6 by the way will compute the whole thing, and throw an exception if it's null...
an example is
if(strString != null && strString.Length > 0)
This line would cause a null exception if both sides executed.
Interesting side note. The above example is quite a bit faster than the IsNullorEmpty method.
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.