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.
#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;
}
||
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With