邏輯運算符 ||, && 的短路規則:
|| 從左向右開始計算,當遇到為真的條件時停止計算,整個表達式為真;所有條件為假時表達式才為假。
&& 從左向右開始計算,當遇到為假的條件時停止計算,整個表達式為假;所有條件為真時表達式才為真。
分析兩個例子:
#include <stdio.h>
int main()
{
int i = ;
int j = ;
if( ++i > || ++j > )
{
printf("%d\n", i);
printf("%d\n", j);
}
return ;
}
前++,執行完++之後參加運算。
輸出結果i=1 j=0,因為第一個條件為真,直接判斷為真。
#include <stdio.h>
int g = ;
int f()
{
return g++;
}
int main()
{
if( f() && f() )
{
printf("%d\n", g);
}
printf("%d\n", g);
return ;
}
上面程式隻輸出一個1,return g++;先傳回g,後對g進行++,是以第一個條件為假,f()隻調用1次,g隻加了1次,隻輸出一個1.
邏輯運算符!
C語言中的邏輯符“!”隻認得0,隻知道見了0就傳回1。是以當其作用的值不是0時,其結果為0。
舉例:
#include <stdio.h>
int main()
{
printf("%d\n", !);
printf("%d\n", !);
printf("%d\n", !);
printf("%d\n", !-);
return ;
}
第一個輸出1,其餘都為0.
三目運算符
三目運算符(a?b:c)可以作為邏輯運算符的載體
規則:當a的值為真時,傳回b的值;否則傳回c的值,注意是傳回”……的值“。
舉例分析:
#include <stdio.h>
int main()
{
int a = ;
int b = ;
int c = ;
c = a < b ? a : b; //c的值為,a小于b,是以将a的值賦給c
(a < b ? a : b) = ; //此處有錯誤,三目運算傳回的a的值,不能作左值
printf("%d\n", a);
printf("%d\n", b);
printf("%d\n", c);
return ;
}
應當把程式改為
*(a<b ? &a : &b) = 3;
這樣就是把a指派為3,這樣程式的輸出就是3,2,1。