Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between & and && in C?

What is the difference between & and && in C?

My teacher gave me this example:

int a = 8;
int b = 4;
printf("a & b = %d\n", a & b);
printf("a && b = %d\n", a && b);

Output:

a & b = 0;
a && b = 1;

I'm not sure why this would return true in one scenario and false in another.

like image 622
sadsa dadasd Avatar asked Apr 02 '18 19:04

sadsa dadasd


2 Answers

The & operator performs a bit-wise and operation on its integer operands, producing an integer result. Thus (8 & 4) is (0b00001000 bitand 0b00000100) (using a binary notation that does not exist in standard C, for clarity), which results in 0b00000000 or 0.

The && operator performs a logical and operation on its boolean operands, producing a boolean result. Thus (8 && 4) is equivalent to ((8 != 0) and (4 != 0)), or (true and true), which results in true.

like image 57
David R Tribble Avatar answered Sep 28 '22 04:09

David R Tribble


& is bitwise and and && is logical and.

The expression x && y will return 1 if both x and y is non-zero, and 0 otherwise. Note that if x is zero, then y will not be evaluated at all. This will matter if y is an expression with side effects. This behviour is called short circuiting.

The expression x & y will perform a bitwise operation on each individual bit in x and y. So if x is 1010 in binary and y is 1100 then x & y will evaluate to 1000. Note that the return value of x & y should NOT be interpreted as a Boolean value, even if it's possible. In early C, the operator && did not exist, and because of that & was used for this purpose.

One way to explain it is that you could imagine that & is the same thing as applying && on each individual bit in the operands.

Also note that & has lower precedence than &&, even though intuition says that it should be the other way around. This also goes for comparison operators, like <, <=, ==, !=, >=, >. This goes back to the time when C did not have the operators && and || and the bitwise versions was used instead. At this time, it made sense, but when the logical operators were added, it did not anymore. Kernighan and Ritchie admitted that it would have made more sense, but they did not fix it because this would break existing code.

I'm not sure why this would return true in one scenario and false in another.

The return value from x & y should not be treated as a Boolean value at all. However, it can (depending on how the code is written) be treated as a Boolean array. If you have two integers, flags1 and flags2 then the result of flags1 & flags2 will denote which flags that are toggled in both flags1 and flags2.

like image 45
klutt Avatar answered Sep 28 '22 05:09

klutt