Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C have both logical and bitwise ‘or’ operators?

Why C has both || and | operators? As far I know, | operator can replace || in conditions because it will return true (nonzero) value when at least one of operands is nonzero.

I ask just out of my curiosity. I know I should use || for logical expressions.

Example

#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;
}
like image 516
jiwopene Avatar asked Dec 18 '22 14:12

jiwopene


1 Answers

|| and | are very different beasts.

Aside from || having the short-circuting property (the right operand is only evaluted if the left one evaluates to 0), it's also a sequencing point.

The value of the expression can also be different: 1 || 2 for example is 1 whereas 1 | 2 is 3.

(Note that && and & have a more pernicious difference, for example 1 && 2 is 1 whereas 1 & 2 is 0.)

like image 100
Bathsheba Avatar answered Dec 31 '22 02:12

Bathsheba