为什么 C 有逻辑和按位“或”运算符?

jiw*_*ene 4 c if-statement bitwise-operators logical-operators

为什么 C 有||and|运算符?据我所知,|运算符可以||在条件中替换,因为当至少一个操作数非零时,它会返回真(非零)值。

我只是出于好奇而问。我知道我应该||用于逻辑表达式。

例子

#include <stdio.h>

int main(void) {
    int to_compare = 5;

    /* Try with bitwise or */
    if ((5 > to_compare) | (to_compare == 6)) {
        printf("‘to_compare’ is less than or equal to 5 or equal to 6.\n");
    }

    /* Try with logical or */
    if ((5 > to_compare) || (to_compare == 6)) {
        printf("‘to_compare’ is less than or equal to 5 or equal to 6.\n");
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 7

||并且|是非常不同的野兽。

除了||具有短路特性(仅当左操作数计算为 0 时才计算右操作数),它也是一个排序点。

表达式的值也可以不同:1 || 2例如 is 1while 1 | 2is 3

(请注意,&&and&有一个更有害的差异,例如1 && 2is 1While 1 & 2is 0。)