Difference Between & and && in C Language

& and && can both be used as logical AND operators, representing logical conjunction (and). The entire result is true only when the results of the expressions on both sides of the operator are true; otherwise, if either side is false, the result is false.

&& also has a short-circuit feature, meaning that if the first expression is false, the second expression is not evaluated. For example, in the expression <pre><code class="language-java">if(str != null && !str.equals("")

, when <pre><code class="language-java">str

is null, the subsequent expression will not execute, so a NullPointerException will not occur. If you change && to &, it will throw a NullPointerException. In <pre><code class="language-java">If(x==33 & ++y>0)

, <pre><code class="language-java">y

will increment, while in <pre><code class="language-java">If(x==33&& ++y>0)

, it will not increment.

& can also be used as a bitwise operator. When the expressions on either side of the & operator are not boolean types, & represents a bitwise AND operation. We typically use 0x0f to perform & operations with an integer to obtain the lowest 4 bits of that integer. For example, the result of <pre><code class="language-java">0x31 & 0x0f

is 0x01. Assuming <pre><code class="language-java">x=7

, what is the result of <pre><code class="language-java">x&&8

? What is the result of <pre><code class="language-java">x&8

? The former results in 1, while the latter results in 0!

&& is the logical AND operator: a && b. The value is true only when both a and b are true.

& is the bitwise AND operator.

7 & 8

is equivalent to 00000111 & 00001000 = 00000000.

It performs AND operation bit by bit.

Some may think that 8 & 8 should be 1, but it returns 8 when executed. Why is that?

8 & 8

0000 1000

& 0000 1000

————

0000 1000

It is still 8.

Additionally, & is generally used as an address operator. For example, defining an array a[], &a points to the address of the first element of the array.

Author: 冰零分子

Difference Between & and && in C Language

Leave a Comment