#include
int main() {
int a = 5;
int b = 10;
if (a > 0 && b > 0) {
printf("Both a and b are positive numbers.
");
} else {
printf("At least one of the numbers is not positive.
");
}
return 0;
}
在這個(gè)例子中,我們檢查變量 a 和 b 是否都大于0,只有當(dāng)兩個(gè)條件都滿足時(shí),即 a > 0 和 b > 0 都為真時(shí),if 語(yǔ)句中的代碼塊才會(huì)執(zhí)行。
示例2: 短路行為的利用
#include
int main() {
int x = 0;
int y = 10;
if (x != 0 && y / x > 1) {
printf("y is greater than x.
");
} else {
printf("Cannot divide by zero or y is not greater than x.
");
}
return 0;
}
在這個(gè)例子中,我們首先檢查 x 是否不等于0,然后才檢查 y / x > 1,由于邏輯與運(yùn)算符的短路行為,x 等于0,則不會(huì)嘗試執(zhí)行除法操作,從而避免了潛在的除以零錯(cuò)誤。
示例3: 邏輯與和位與的區(qū)分
#include
int main() {
int a = 60; // 二進(jìn)制表示為 0011 1100
int b = 13; // 二進(jìn)制表示為 0000 1101
// 位與操作
int bitwise_result = a & b; // 結(jié)果為 0000 1100 (十進(jìn)制的 12)
printf("Bitwise AND result: %d
", bitwise_result);
// 邏輯與操作
if (a > 0 && b > 0) {
printf("Both a and b are positive numbers.
");
} else {
printf("At least one of the numbers is not positive.
");
}
return 0;
}
在這個(gè)例子中,我們展示了位與(&)和邏輯與(&&)的區(qū)別。a & b 計(jì)算的是 a 和 b 的位與結(jié)果,而 a > 0 && b > 0 是一個(gè)邏輯表達(dá)式,檢查 a 和 b 是否都是正數(shù)。