-2

| is an OR and & is AND.

I have the following code and they works OPPOSITE.

            int a = 0;
            int b = 0;
            int c = -1;
            if ((a | b | c) == 0) 
            {
                textBox8.Text = "everything 0"; 
            }
            else
            {
                textBox8.Text = "something is not a 0"; // <- code goes here
            }            
            if ((a & b & c) == 0)
            {
                textBox9.Text = "everything 0";  // <- code goes here            
            }
            else
            {
                textBox9.Text = "something is not a 0";               
            }

why i have this result?

https://i.stack.imgur.com/0Afv6.jpg

  • 1
    because `(a & b & c) == 0` doesn't mean "everything 0" but "there is no common bits setted" – Selvin Mar 26 '21 at 13:02
  • Are you confusing _bitwise_ or `|` with _logical_ or `||`? – gunr2171 Mar 26 '21 at 13:05
  • 1
    [What is the difference between the | and || or operators?](https://stackoverflow.com/questions/35301/what-is-the-difference-between-the-and-or-operators) – gunr2171 Mar 26 '21 at 13:08
  • `a == 0 && b == 0 && c ==0` ... you have to use && for `and` and || for Or – Jawad Mar 26 '21 at 13:09
  • 3
    @Jawad Actually if you do it that way you can use `&` since you're now dealing with `bool` values and that will behave as a logical and. However the `&&` will short circuit and stop comparing at the first `false` value. One reason to always use `||` and `&&` for logical operations is that you can not accidently apply them to anything that isn't `bool`. – juharr Mar 26 '21 at 13:11
  • related [What does a single | or & mean?](https://stackoverflow.com/questions/9736751/what-does-a-single-or-mean?noredirect=1&lq=1) – Self Mar 26 '21 at 13:27

1 Answers1

2

(a | b | c) == 0 does NOT mean "a is zero or b is zero or c is zero". For that you'd need (a==0 | b==0 | c==0) (you could also use ||, which stops evaluating after one operand is true).

With numeric operands, | is a bitwise "OR" operator, which you can read about separately. || is not valid for anything other than boolean operands, so it can be useful to be in the habit of using || unless you explicitly don't want short-circuiting. That way you don't ever accidentally use it as a bitwise operator when you indented to use it as a logical operator. (it would have been a compiler error in this instance, for example).

D Stanley
  • 149,601
  • 11
  • 178
  • 240