0

Say I have 2 comparison

if ((length >= 524288) | (length == 0))
{
      //do something...
}

vs

if ((length >= 524288) || (length == 0))
{
      //do something...
}

are these the same thing since when you bitwise OR 0001 0000 it turns into 1? Also is there any particular reason to use bitwise OR in this situation?

Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • 4
    No. `if (p == NULL || p->n > 10)` is OK, but `if ((p == NULL) | (p->n > 10))` has undefined behaviour. – Kerrek SB Aug 31 '16 at 20:48
  • 1
    @AndrewL. That answer is for C# is that the same as C? – Lightsout Aug 31 '16 at 20:51
  • They are the same exact operators and these operators are universal in their operation – Andrew Li Aug 31 '16 at 20:51
  • @KerrekSB Is there any particular reason to use | in this situation? I am trying to read through a piece of arduino code and I have no idea why the author used bitwise OR. – Lightsout Aug 31 '16 at 20:59
  • @bakalolo: No. Never underestimate the likelihood of seeing bad code in the wild. – Kerrek SB Aug 31 '16 at 21:41
  • You would use bitwise or for branchless code or in this case to minimize the number of branches... To help with branch prediction, help the compiler vectorize or prevent timing attacks ... Micro-optimizations basically. – technosaurus Sep 01 '16 at 01:38

1 Answers1

2

In that case bitwise = logical since both tests return 0 or 1.

The only difference with single | is that both parts of the test will be executed whatever the result of the first test => use || here.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219