This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does the compiler continue evaluating an expression where all must be true if the first is false?
Difference between eager operation and short-circuit operation? (| versu || and & versu &&)
So here's my question. If I have this
if (Foo() && Bar())
DoStuff();
if Foo() returns false, will it still run through Bar()? or do I need to have
if (Foo())
if (Bar())
DoStuff();
to ensure that it only runs through the minimum amount needed before "failing out"?
if (Foo() && Bar())
In this case (logical AND) it will firstly check Foo() return value and will do Bar() only if Foo() returns true. Simply if any of conditions is false then it will not check others, it will check conditions from left to right.
No, Bar() won't be evaluated if Foo() returns false. It's a feature of the C# && operator (not limited to if statements):
The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
What you are looking for is called "Short-circuiting," and yes, .Net supports it.
Related
Is there a way to make the C# compiler optimize my OR clauses in an if statement?
For example:
if(Function_that_returns_boolean() || boolean_value)
{
// Do something here...
}
Could have hugely different execution times than
if(boolean_value || Function_that_returns_boolean())
{
// Do something here...
}
depending on how much work Function_that_returns_boolean() actually does internally.
It's unlikely (and perhaps impossible) that the compiler could know exactly how efficient Function_that_returns_boolean() is, and all of my (brief) testing indicates OR statements are always processed left to right, even under using the most aggressive compiler optimizations.
Is this already handled by the compiler (i.e. am I mistaken)? If not, are there any hints I can give to it?
Maybe something like an Attribute that lets the compiler know that it's free to rearrange my code (and if not present, to leave it be)?
[OrStatementUsage(Speed.Fast)] // Always push statement left when possible
public bool Fast_function_that_returns_boolean()
{
return a + b == c; // fast
}
[OrStatementUsage(Speed.Slow)] // Always push statement right when possible
public bool Slow_function_that_returns_boolean()
{
Thread.Sleep(1000);
return a + b == c; // slow
}
(Note: all methods in the statement would have to be tagged and side-effect free to be candidates for rearrangement)
http://msdn.microsoft.com/en-us/library/6373h346.aspx
The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.
The first operand will always be evaluated. This is a very important guarantee:
if (obj == null || obj.foo == "bar")
If the compiler could reorder the conditions here, it would change the functionality of the program.
The compiler can't know whether a given reordering would affect the result -- both because it can't in general know what the result will be and because it doesn't know what parts of the result are important. Maybe you want a long delay, or the first calculation does something important for the correctness of the program.
No, the first argument is evaluated, and if it is true, the second argument is not evaluated at all. It is called "short-circuit" evaluation.
See http://msdn.microsoft.com/en-us/library/6373h346.aspx.
There is no way to instruct the compiler to evaluate the second argument of || first.
No, boolean logic operators are always short-circuit evaluated. In case of an or, the second part might not even be evaluated if it already evaluated to true. For instance:
if(ReturnTrue() || SlowOperation()) { /* ... */ }
Assuming that ReturnTrue() returns true, SlowOperation() is never called. The compiler cannot make optimization based on some arbitrary assumptions
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Will all methods in a logical expressions be executed?
Let me explain: let's say we have theese two codes:
foreach(Object o in Objs)
if(o is Class1 || o is Class2)
DoSomething();
__
foreach(Object o in Objs)
if(o is Class1)
DoSomething();
else if(o is Class2)
DoSomething();
Now, of course an OR is better in this case, but my question is different and just out of curiosity: when in the first case o is of type Class1, does the compiler stop and run the code or it checks what comes next anyway?
It would do that in the second case.
|| is short-circuiting, which means: if the first argument returns true, the second argument is not evaluated. In this way, yes it is broadly equivalent to your second example, but more terse.
MSDN Documentation for the || operator in C#
The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.
Note: That is also the case for all C-like languages (C, C++, Java, C#) that I know of.
In the operation x || y, y is evaluated only if x is false.
Yes.
The double pipe or "||" will look from the left to the right if some condition is true, whether it will stop looking for other condition and execute the piece of code. The simple pipe or "|" will do the same thing but will check all the conditions (so generally you will prefer using "||").
I have a bunch of methods that all return a bool.
If one method returns false then there is no value in calling the following methods, especially as some of them are 'expensive' operations.
Which is the more efficient?
bool result = method1();
if (result) result = method2();
if (result) result = method3();
return result;
or
return method1() && method2() && method3();
As I understand it, the 2nd form should stop evaluating as soon as one of the methods returns false, right?
Yes you are right. Both && and || boolean operators in c# work as short-circuit operator. It stops evaluating expression once its value is determined. It stops unnecessary execution.
Hence return method1() && method2() && method3(); is better option in your case. If you have something in non-evaluated statement, say method3 in your case, it may lead to some side effects.
There is this very good language independent article about short-circuit operators on Wikipedia.
UPDATE:
In C# if you want to use logical operator without short-circuit, use & and | operator instead.
Yes, the two methods are equivalent. Using && is a shortcut to achieve the same result as using a backing variable.
The second will stop the expression evaluation after the first expression is evaluated to false.
although both examples are semantically equivalent the second one is more readable in my opionion.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why must we define both == and != in C#?
Why is overloading of += possible only by overloading of +, but == and != are separately overloaded?
It seems it should be inverted.
+= overloading is nearly always possible to write more effective because it's unnecessary to allocate memory for new object. But I can't invent an example in which operators == and != should be different in something except inverting the result Equals().
A similar question has been asked before.
The biggest reason is that when you overload the == and != operators, you don't have to return a boolean. If you're not returning a boolean, you can't just invert the complimentary operator. There are other possible reasons they are separately overloaded, you can view the answers to that question for those other reasons.
There is a valid reason you can't overload += and therefore it is done implicitly via the + operator. I has to do with the fact that you can't override the assignment operator in C#, it's part of the language standard. The += is increment and assign, the latter of which you can't overload in C#.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
== Operator and operands
Possible Duplicates:
Is there any difference between if(a==5) or if(5==a) in C#?
== Operator and operands
Ok, this may be stupid question, but searching in google (cant seem to ACTUALLY search for an exact phrase even with quotes)
What if any difference is there between
if(false == <somecondition>){
and
if(<somecondition> == false){
in C#? I am familiar with c#'s expression evalution, and understand how the order would make sense if you were doing something like:
if(AccountIsInvalid || AccountIsUnregistered)
I dont need a huge lesson, but would like to understand why some people prefer to do things with false==.... route.
Personally, I never compare anything to false or true.
I would go with:
if (!somecondition)
or:
if (somecondition)
In C there would have been, perhaps, some reason to do this as you could easily make a mistake and use the assignment operator instead of the comparison operator, but in C# it shouldn't make any difference -- you'll get a compile warning if you use the assignment operator. If the assignment were a different type (say int), it would result in an error, since the result wouldn't be a legal expression for the if statement.
I would prefer it to be
if (!<somecondition>)
{
...
}
rather than a comparison to false (or true, for that matter).
Before performing any optimizations or short-circuits, the compiler needs to resolve <somecondition> to true or false value, thus there is no reason why the compiler would evaluate the expressions <somecondition> == false and false == <somecondition> any differently.
This must surely be an issue of style, and style only.
This doesn't matter in C# like it does in c/c++ because conditions must evaluate to a boolean.