0

I was decoding a c++ code and did not understand why is the vertical bar is used in the 6th line.

void build(int id, int l, int r) {
  if (l == r) {
    sum[id] = a[l];
    return;
  }
  int mid = (l + r) >> 1;
  build(id << 1, l, mid);
  build(id << 1 | 1, mid + 1, r); /*what operation does vertical
                                 bar perform with bitwise operator*/
  sum[id] = max(sum[id << 1], sum[id << 1 | 1]);
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

2 Answers2

2

This code

build(id<<1,l,mid);
build(id<<1|1,mid+1,r);

is equivalent to

build(2*id, l, mid);
build(2*id+1, mid+1, r);

The only difference is the first has been written by someone who thinks (wrongly) that it's more efficient than the second. A good programmer would prefer the second because it's easier to understand.

john
  • 85,011
  • 4
  • 57
  • 81
  • Most programmers would prefer the first, because it is easier to understand -- shifting in a 1 bit. Mixing shift and add is more complex and harder to understand. – Chris Dodd Jul 21 '19 at 04:44
  • 1
    @ChrisDodd I didn't mix shift and add. – john Jul 21 '19 at 04:47
1

The | is a bitwise or. It takes two numbers as operands and does OR on each bit of the two numbers.

For example, consider the ORing of the following tow bit patterns: 00011010 | 10000111 = 10011111

ManLaw
  • 115
  • 1
  • 10