vendredi 13 décembre 2019

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;
}

Aucun commentaire:

Enregistrer un commentaire