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 "||").
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:
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.
Well I have been reading quite a lot sources but they differ in definiton:
&& is logical operator of logical
conjunction //I guess this is correct
&& is operator of logical AND //I
think this is not precise from
technical point of view
&& is
conditional operator performing
logical AND //I think this is right
as well
While all are correct in terms of understanding, I would say the first one is most precise. Or am I mistaken?
In C#, Java, C++, C, and probably several other languages, && is a programming language implementation of the boolean AND operator. It is designed to account for the following facts (that do not apply in pure propositional logic):
Evaluating an operand may be computationally expensive
Evaluating an operand may fail with an exception
Evaluating an operand may enter an infinite loop
So a boolean expression in a programming language really has four possible outcomes: true, false, "exception", and "infinite loop". In some situations, one has two boolean expressions where the possible success of the second expression can be determined by looking at the first expression. For instance, with the expressions foo != null and foo.bar == 42, we can be certain that if the first expression is false, then the second expression will fail. Hence, the && operator is designed to be "short-cirquited": If the left operand evaluates to false, the right operand is not evaluated. In all cases where both operands would evaluate successfully to true or false, this rule produces the same result as if one actually had evaluated both operands, but it allows for increased performance (because the right operand might not need to be evaluated at all) and increased compactness without sacrificing safety (if one takes care to structure the expression such that the left operand "guards" the right one). Similarly, || will not evaluate the right operand if the left operand evaluates to true.
A shorter answer is that although && is strongly inspired by AND, it is designed to take certain programming peculiarities into account, and a && b should perhaps rather be phrased as "an expression that returns false if a is false, and the value of b if a is true".
The easy answer.
It performs an AND operation on 2 logical expressions returnting a Boolean. It does not evaluate the second if the first is false.
To evaluate both regardless use &.
The complicated answer.
http://www.ecma-international.org/publications/standards/Ecma-334.htm heading 12.3.3.23 seems most relavent.
I find myself unqualified to criticise the definition within.
12.3.3.23 && expressions
For an expression expr of the form expr-first && expr-second:
• The definite assignment state of v before expr-first is the same as the definite assignment state of v before expr.
• The definite assignment state of v before expr-second is definitely assigned if the state of v after exprfirst is either definitely assigned or “definitely assigned after true expression”. Otherwise, it is notdefinitely assigned.
• The definite assignment state of v after expr is determined by:
o If the state of v after expr-first is definitely assigned, then the state of v after expr is definitely assigned.
o Otherwise, if the state of v after expr-second is definitely assigned, and the state of v after expr-first is “definitely assigned after false expression”, then the state of v after expr is definitely assigned.
o Otherwise, if the state of v after expr-second is definitely assigned or “definitely assigned after true expression”, then the state of v after expr is “definitely assigned after true expression”.
o Otherwise, if the state of v after expr-first is “definitely assigned after false expression”, and the state of v after expr-second is “definitely assigned after false expression”, then the state of v after expr is “definitely assigned after false expression”.
o Otherwise, the state of v after expr is not definitely assigned.
[Example: In the following code
class A
{
static void F(int x, int y) {
int i;
if (x >= 0 && (i = y) >= 0) {
// i definitely assigned
}
else {
// i not definitely assigned
}
// i not definitely assigned
}
}
the variable i is considered definitely assigned in one of the embedded statements of an if statement but not in the other. In the if statement in method F, the variable i is definitely assigned in the first embedded statement because execution of the expression (i = y) always precedes execution of this embedded statement. In contrast, the variable i is not definitely assigned in the second embedded statement, since x >= 0 might have tested false, resulting in the variable i’s being unassigned. end example]
I hope that clears things up.
Conjunction is another word for "and". So they're all correct in terms of their output.
In terms of how they actually give the output, && usually doesn't evaluate the second argument if the first one is false.
In C#, can you use a boolean predicate on its own as the parameter for an if statement?
eg:
string str = "HELLO";
if (str.Equals("HELLO"))
{
Console.WriteLine("HELLO");
}
Will this code output "HELLO", or does it need to be:
string str = "HELLO";
if (str.Equals("HELLO") == true)
{
Console.WriteLine("HELLO");
}
If there is anything else wrong with the above code segments, please point it out.
EDIT: double equals as per answers
Well, the latter snippet won't even compile because it's trying to assign true to str.Equals("Hello") (you've got a single = instead of ==) but either:
if (str.Equals("HELLO"))
or
if (str.Equals("HELLO") == true)
will work. The latter is pretty strongly discouraged though - it's pretty ugly.
Bear in mind that string overloads ==, so you can actually write:
if (str == "HELLO")
which is somewhat simpler.
The second version won't even compile, since you need ==, not =.
Seeing code like if (foo == true) makes bile rise up into my mouth.
Yes you can.
(Your second example needs 2 = (i.e. ==) to be correct).
can you use a boolean predicate on its own as the parameter for an if statement
Strictly speaking, the answer to this is 'no', because a predicate is a function (in the mathematical sense). What you can use for the conditional expression in an if is any boolean expression, including (as here) the result of the invocation of a predicate on a value.
To expand, the 'predicate' here is 'equals HELLO'. It is a function (in the mathematical sense) that operates on values of type string, and returns boolean values. Once you have obtained a boolean value (by applying this function to a particular string, str), you do not need to explicitly compare it to true: you can just use it.
As you will see from others' answers, code in which expressions of boolean type are explicitly compared to boolean literals will often cause code-style pain in the reader :) (My 'favourite' peeve is <boolean expression> ? true : false).
The code you have is correct, the if statement checks to see if the statement within the brackets evaluates to true.
Remember that comparisons in c# use == not = , so it should be if (x == true)
This can be used in other situations like:
bool isACat = true;
if (isACat)
{
}
It is good practice to put is or a similar identifier (Is/Has/Should/Will/Do/Must...) before boolean variable names, as it makes it easy to read when you are not using == true.
There's nothing wrong.
Just two different ways of picking up the same spoon to feed yourself ;)
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.