What is the difference between & and &&operators?

Asked

Viewed 4,422 times

25

I was making a simple code with a if two conditions. Everything worked normal and after I went to read, I realized I had written condicao & condicao2 instead of using &&. Even with this "typo" the code is fully functional.

A simple example where the two WriteLine are executed. The example can be executed on . NET Fiddle

bool condicao1 = true, condicao2 = true;

if(condicao1 && condicao2)
    WriteLine("Primeiro if - OK");

if(condicao1 & condicao2)
    WriteLine("Segundo if - OK");

What is the name of the operator &?

Will these operators always be interchangeable? If so, is there a difference between using one and the other? If not, what is the semantic difference between the two?

4 answers

21


The & is the bit operator and, then it compares each bit of the verified data and results in 1 whenever the corresponding bit in the two operands is 1, after all the and is only true when both are true, otherwise the result will be 0, and so bit manipulation.

This is his primary function and knowing how to use it well can make some optimizations (not that always need) avoiding that exist branches unnecessary that it is a very costly processor operation. Operations with it can be seen in How to connect a bit to a number?.

Of course, if you do this on a boolean die, only 1 bit is relevant, and they will be calculated and the result can be used as a boolean, so it serves as a boolean if, for example.

It is necessary to understand that the if only accepts a boolean. So it can only apply to operands that are worth 00000000 or 00000001 and are of the boolean type. Only the last bit is relevant, without considering endianess.

In a more complex Boolean expression with more than one subexpression this operator will always execute all subexpressions (the operands of &), no matter what the result, in some cases it is what you want, in others you do not need to worry about the second subexpression when the result of the first is 0 (false), so you can use the &&.

The && is the and logical and does not work with bits, only with the boolean result. It has short-circuit, then it only executes the second subexpression if the first one is true.

The same goes for the | and ||, only in this case it is a or, then on || if the first is true does not execute the second because it is sufficient for a subexpression to be true for everything to be considered true.

using static System.Console;

public class Program {
    public static void Main() {
        var x = 1;
        var y = 2;
        var a = x & y;
        var b = x == 1;
        var c = y == 2;
        var d = x & y;
        var e = (x & y) == 0;
        WriteLine(a);
        WriteLine(d); //note que é um inteiro
        WriteLine(e);
        //if (x & y) WriteLine("ok"); //não funciona porque if espera um bool e o resultado é int
        if (b & c) WriteLine("ok"); else WriteLine(" não ok");
        if (Teste(x) & Teste(y)) WriteLine("&  - ok"); else WriteLine("&");
        if (Teste(x) && Teste(y)) WriteLine("&& - ok"); else WriteLine("&&");
        if (Teste(x) | Teste(y)) WriteLine("|  - ok"); else WriteLine("|");
        if (Teste(x) || Teste(y)) WriteLine("|| - ok"); else WriteLine("||");
        if (Teste(y) & Teste(x)) WriteLine("&  - ok"); else WriteLine("&");
        if (Teste(y) && Teste(x)) WriteLine("&& - ok"); else WriteLine("&&");
        if (Teste(y) | Teste(x)) WriteLine("|  - ok"); else WriteLine("|");
        if (Teste(y) || Teste(x)) WriteLine("|| - ok"); else WriteLine("||");
    }
    public static bool Teste(int x) {
        WriteLine($"Executou {x}");
        return x == 2;
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

You can see more in What are the operators for | & << >>?.

To truth table determines the Boolean algebra results.

Tabela verdade

14

there is some difference between using one and the other?

Yes.


Compare with two & means to make Circuit short. Ex:

if((condicao1) & (condicao2)) { }

In doing so, Runtime will check the two conditions before deciding whether the result is true or false. In an expression AND, if one of the conditions is false, no matter how many other conditions are positive, the result will be false.

In doing:

if((condicao1) && (condicao2)) { }

If the first condition is false, Runtime won’t even waste time calculating/solving the second, because it knows that the result of the whole will be false.


Truth table:

| A | B | S |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |

Here has an operator documentation link && which explains exactly that.

2

As mentioned, the && is a logical operator, usually used for conditional operation.

if(x > 0 && x < 20){ ... }

& Simple has a slightly different functionality as it works on bits. In general & is widely used in microcontroller programming for example, where you apply bit masks to disable an output

portA = readPortA();
portA = portA & 0b11111110;
writePortA;

This pseudo code would be disabling the PORT output 0, since a possible reading would be:

//estado lido: 0b01010101
//estado retornado: 0b01010100

portA = readPortA();
// portA = 0b01010101
portA = portA & 0b11111110;
// força o ultimo bit a 0
// 0b01010101 & 0b11111110 = 0b01010100
writePortA;

-3

The && you compare the two expressions: 1==1&& 2==2=> will only be true if both conditions are true. He’s short-circuited, so he only runs the second half if the first one is real. & Is the same thing most unlike && does not short-circuit and has bit-by-bit comparison.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.