Csharp/CSharp Tutorial/Operator/Short Circuit Operators — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Side-effects of short-circuit operators
using System;
class Example {
public static void Main() {
int i;
bool someCondition = false;
i = 0;
Console.WriteLine("i is still incremented even though the if statement fails.");
if(someCondition & (++i < 100))
Console.WriteLine("this won"t be displayed");
Console.WriteLine("if statement executed: " + i); // displays 1
Console.WriteLine("i is not incremented because the short-circuit operator skips the increment.");
if(someCondition && (++i < 100))
Console.WriteLine("this won"t be displayed");
Console.WriteLine("if statement executed: " + i); // still 1 !!
}
}
i is still incremented even though the if statement fails. if statement executed: 1 i is not incremented because the short-circuit operator skips the increment. if statement executed: 1
The short-circuit operators
The short-circuit AND operator is && and the short-circuit OR operator is ||.
As described earlier, their normal counterparts are & and |.
The normal operands will always evaluate each operand, but short-circuit versions will evaluate the second operand only when necessary.
using System;
class Example {
public static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
d = 0; // now, set d to zero
Console.WriteLine("Since d is zero, the second operand is not evaluated.");
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
Console.WriteLine("try the same thing without short-circuit operator. This will cause a divide-by-zero error.");
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
}
}
2 is a factor of 10 Since d is zero, the second operand is not evaluated. try the same thing without short-circuit operator. This will cause a divide-by-zero error. Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at Example.Main()