刚才在论坛看帖:http://community.csdn.net/Expert/topic/5629/5629827.xml?temp=.544018
遇到一个问题,当逻辑判断句中与或连用,又没加括号,执行的顺序会是怎样的呢?
如:
false && false || true
这 个逻辑判断的最终结果应该是什么呢?
以前认为与或的优先级相同,当它们连用时,我总是加上括号,不加括号时会怎样,忘记了。我在猜测从左到右,还是从右向左.在做了一些测试之后,发现都不对.后来想到是不是"先与后或",脑中好像有那么一点印象,不敢断言,所以请教了一个朋友,得到确认.是"先与后或".在SQL和C#中分别做了一些测试,确实是这样.
不过,我认为加上括号还是好习惯。
附:我的测试代码
SQL:
if
(
1
>
2
or
1
>
2
and
1
<
2
)
--
false or false and true
print 1
else
print 0
-- result--------------
0 false
if ( 1 < 2 or 1 > 2 and 1 > 2 ) -- true or false and false
print 1
else
print 0
-- result--------------
1 true
if ( 1 < 2 or 1 > 2 and 1 < 2 ) -- true or false and true
print 1
else
print 0
-- result--------------
1 true
if ( 1 < 2 and 1 > 2 or 1 < 2 ) -- true and false or true
print 1
else
print 0
-- result--------------
1 true
if ( 1 > 2 and 1 > 2 or 1 < 2 ) -- false and false or true
print 1
else
print 0
-- result--------------
1 true
if ( 1 > 2 and 1 > 2 or 1 < 2 or 1 > 2 and 1 < 2 or 1 > 2 and 1 > 2 ) -- false && false || true || false && true || false && false
print 1
else
print 0
-- result--------------
1 true
print 1
else
print 0
-- result--------------
0 false
if ( 1 < 2 or 1 > 2 and 1 > 2 ) -- true or false and false
print 1
else
print 0
-- result--------------
1 true
if ( 1 < 2 or 1 > 2 and 1 < 2 ) -- true or false and true
print 1
else
print 0
-- result--------------
1 true
if ( 1 < 2 and 1 > 2 or 1 < 2 ) -- true and false or true
print 1
else
print 0
-- result--------------
1 true
if ( 1 > 2 and 1 > 2 or 1 < 2 ) -- false and false or true
print 1
else
print 0
-- result--------------
1 true
if ( 1 > 2 and 1 > 2 or 1 < 2 or 1 > 2 and 1 < 2 or 1 > 2 and 1 > 2 ) -- false && false || true || false && true || false && false
print 1
else
print 0
-- result--------------
1 true
C#:
class
Program
... {
static void Main(string[] args)
...{
Console.WriteLine("false || false && true={0}", false || false && true);
Console.WriteLine("true || false && false={0}", true || false && false);
Console.WriteLine("true || false && true ={0}", true || false && true);
Console.WriteLine("true && false || true ={0}", true && false || true);
Console.WriteLine("false && false || true ={0}", false && false || true);
Console.WriteLine("false && false || true || false && true || false && false ={0}", false && false || true || false && true || false && false);
Console.ReadLine();
}
}
... {
static void Main(string[] args)
...{
Console.WriteLine("false || false && true={0}", false || false && true);
Console.WriteLine("true || false && false={0}", true || false && false);
Console.WriteLine("true || false && true ={0}", true || false && true);
Console.WriteLine("true && false || true ={0}", true && false || true);
Console.WriteLine("false && false || true ={0}", false && false || true);
Console.WriteLine("false && false || true || false && true || false && false ={0}", false && false || true || false && true || false && false);
Console.ReadLine();
}
}