There are many questions on the net that refer to the differences between bitwise and logical operators. Hoping that I have done a good search, none of them specialize to whether they are the same or not when used inside conditional statements nor refer exclusively to C Language. The majority referred to C++ and C# and I do not know if the same answers were applicable to C Language too.
This is an example code I wrote to test what is going on:
// Difference between logical && and bitwise & //
#include <stdio.h>
#define TRUE 123>45
#define FALSE 4>2342
void print_tt(int table[][4]);
int main(void) {
int and_tt[2][4]; // AND truth table
int or_tt[2][4]; // OR truth table
// Create truth table for logical and bitwise AND operator all in one 2d array
and_tt[0][0] = TRUE && TRUE ? 1 : 0;
and_tt[0][1] = TRUE && FALSE ? 1 : 0;
and_tt[0][2] = FALSE && TRUE ? 1 : 0;
and_tt[0][3] = FALSE && FALSE ? 1 : 0;
and_tt[1][0] = TRUE & TRUE ? 1 : 0;
and_tt[1][1] = TRUE & FALSE ? 1 : 0;
and_tt[1][2] = FALSE & TRUE ? 1 : 0;
and_tt[1][3] = FALSE & FALSE ? 1 : 0;
// Create truth table for logical and bitwise OR operator all in one 2d array
or_tt[0][0] = TRUE || TRUE ? 1 : 0;
or_tt[0][1] = TRUE || FALSE ? 1 : 0;
or_tt[0][2] = FALSE || TRUE ? 1 : 0;
or_tt[0][3] = FALSE || FALSE ? 1 : 0;
or_tt[1][0] = TRUE | TRUE ? 1 : 0;
or_tt[1][1] = TRUE | FALSE ? 1 : 0;
or_tt[1][2] = FALSE | TRUE ? 1 : 0;
or_tt[1][3] = FALSE | FALSE ? 1 : 0;
puts("_______AND_______");
puts("Logical Bitwise");
print_tt(and_tt);
puts("_______OR________");
puts("Logical Bitwise");
print_tt(or_tt);
}
// prints the truth table of the bitwise and logical operator given side by side
void print_tt(int table[][4]) {
int i;
for(i=0; i<4 ; ++i) {
printf("%-10s%s\n", table[0][i] ? "true" : "false",
table[1][i] ? "true" : "false");
}
}
The program’s output is:
_______AND_______
Logical Bitwise
true true
false false
false false
false false
_______OR________
Logical Bitwise
true true
true true
true true
false false
Which proves that there are no differences between bitwise and logical operators. Changing the definition of TRUE
and FALSE
macros to include the remaining comparison operators, one can see that there is no difference again.
Therefore, if there are differences, these might be associated to the way the compiler interprets the statement or the efficiency of the code.
In conclusion, in the specific case when we have a bitwise or logical operator between two or more results of a comparison operation inside a conditional statement, which of the two should we use, mostly for greater efficiency ?