What is the difference between & & & & &?

19

I was doing a simple code with if of two conditions. Everything worked fine and after I read it, 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 run in .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 any difference between using one and the other? If not, what is the semantic difference between the two?

    
asked by anonymous 16.03.2017 / 18:01

3 answers

14

The & is the and bit operator, so it compares each bit of the checked 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, so it handles bits.

This is the primary function of it and knowing how to use it well you can do some optimizations (not that you need to) always avoiding unnecessary branches which is a very expensive processor operation. Operations with it can be seen in How to connect a bit to a number? .

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

It should be understood that if only accepts a Boolean. Then it can only apply in operands that are 00000000 or 00000001 and is of 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 the result, in some cases it is what you want, in others you do not have to worry about second subexpression when the result of the first is 0 (false), then you can use && .

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

The same goes for | and || , except that in this case it is a or , then in || if the first one is true it does not execute the second because just a subexpression is 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;
    }
}

See running on .NET Fiddle . And No Coding Ground . Also I put it in GitHub for future reference .

You can find out more at What are operators for | & < < > >? .

The truth table determines the results of Boolean algebra.

    
16.03.2017 / 18:21
13
  

Is there a difference between using one and the other?

Yes.

Comparing with two & means doing short circuit . Ex:

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

When doing this, the runtime will check both 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 .

When doing:

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

If the first condition is false, the runtime will not waste time calculating / resolving the second, since it knows that the result will be false .

Truth Table:

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

Here has a link to the documentation for the && operator that explains exactly that.     

16.03.2017 / 18:09
0

As mentioned, & amp; is a logical operator, usually used for conditional operations.

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

O & simple has a slightly different functionality, since it works on bits . In general & is very used in programming microcontrollers for example, where you apply bit masks to disable an output

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

This pseudo code would be disabling PORTA 0 output, 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;
    
16.03.2017 / 19:19