Question

I have the following code and I can't understand what does it mean:

var1 |= var2>0 ? 1 : 2;

Anyone can help me please!

Was it helpful?

Solution

if (var2 > 0)
  var1 = var1 | 1;
else 
  var1 = var1 | 2;

It's bitwise-or.

OTHER TIPS

All the a op= b operators are a shortcut to a = a op b.

However since C++ allows op and op= to be overridden separately you rely on each implementer of custom types to be consistent.

Its the Assignment by bitwise OR

v1 |= v2;

is short for:

v1 = v1 | v2;

cond ? x : y returns x if cond is true and y otherwise. Read Ternary Operator

a |= b is shorthand for a = a | b which is assigning a | b to a

a | b is bitwise OR of a and b. ( e.g. 2 | 3 = 3 and 1 | 2 = 3 )

As others have said it is short for v1 = v1 | v2; Another usage you might come across is with booleans.
Given:

bool b = /*some value*/

Instead of saying:

if(a)
  b = true;

you might see:

  b |= a;

Integers can be represented in binary, so that each digit (bit, switch) is 1 (on) or 0 (off):

00000000  ==  0
00000001  ==  1
00000010  ==  2
00000011  ==  3
00000100  ==  4
00001000  ==  8
00010000  ==  16

Bitwise OR combines two numbers by "merging" the two sets of bits:

First number:     00110000
Second number:    00000010
Result:           00110010

If a bit is 1 in EITHER of the input numbers, then it will be 1 in the result.

Compare with bitwise AND, which finds the "overlap" of the two sets of bits:

First number:     00110100
Second number:    10011110
Result:           00010100

If a bit is 1 in BOTH of the input numbers, then it will be 1 in the result.

If the numbers are in variables a and b, you can place the the bitwise OR/AND results into a new variable c:

unsigned int c = a | b; // OR

unsigned int c = a & b; // AND

Often the result needs to be placed into one of the two variables, i.e.

unsigned int c = a | b; // OR
c = a; // copy

So as a shorthand, you can do this in a single step:

a |= b; // merge b directly into a

As other people before me have mentioned, it means you'll end up with assignments by bitwise OR.

Bitwise OR can be illustrated by taking the left-hand and right-hand side bit-patterns and put them on top of eachother.

In each column: 0 + 0 gives 0, 1 + 0 gives 1, 0 + 1 gives 1, 1 + 1 gives 1.
In the context of booleans: false OR false == false, true OR false == true, false OR true == true, true OR true == true.

Here's an example of bitwise OR and the resulting bit pattern: var1(11) |= var2(14) --> var1(15)

    1011 (11)
OR  1110 (14)  
=   1111 (15)

The operator |= means Assignment by bitwise OR operator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top