So we got this piece of code on a test and I had zero idea what is the meaning and how it works.
unsigned int a = 1, b = 2, c;
and then c = a&b || a&&b;
The question was: What is the value of c
. Answer was 1.
Can somebody explain what is happening in initialization of c
?
This assignment statement
c = a&b || a&&b;
may be rewritten for clarity the followinmg way
c = ( a&b ) || ( a&&b );
a & b
is the bitwise AND operation. As a
is equal to 1
and b
is equal to 2
then the result of the operation is equal to 0
(I am using only 8 bits in the number representations for simplicity)
00000001
&
00000010
========
00000000
From the C Standard (6.5.10 Bitwise AND operator)
4 The result of the binary & operator is the bitwise AND of the operands (that is, each bit in the result is set if and only if each of the corresponding bits in the converted operands is set).
In this expression a && b
there is the logical AND operation. It is equal to 1
when the both operands are unequal to 0
. As a
and b
are unequal to 0
then the result of the operation is 1
.
From the C Standard (6.5.13 Logical AND operator)
3 The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
So you have
c = 0 || 1;
where the logical OR operation is used. It yields 1
if at least one operand is not equal to 0
.
From the C Standard (6.5.14 Logical OR operator)
3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
So the variable c
will be assigned with the value 1
.