Meaning of “| =” operator?

2020-04-12 01:58发布

I have encountered code like

if (flagsDef) 
flagsTainted |= flagsUsed;

please assist in knowing the meaning of the operator used.

标签: c
4条回答
何必那么认真
2楼-- · 2020-04-12 02:50

The statement:

flagsTainted |= flagsUsed

is shorthand for:

flagsTainted = flagsTainted | flagsUsed

which uses the binary/bitwise OR operator |.

The code is manipulating a flag variable, which is keeping state information by setting bits in the variable flagsTainted.

For more information about bitwise manipulation, the wikipedia article is pretty good.

查看更多
smile是对你的礼貌
3楼-- · 2020-04-12 02:53

| is a bitwise OR. This means that it compares the bits using an or operator.

For example:

101
001

If you | the two, you get 101. The | = assigns the result back to the left hand side of the operation.

查看更多
你好瞎i
4楼-- · 2020-04-12 02:59

It can be read in English as "or equals".

It's similar to += except instead of adding the left value to the right, it instead performs a bitwise or of the two values and then assigns the result into the left variable as you would expect.

For more information on bitwise operations, see this link: Wikipedia

查看更多
▲ chillily
5楼-- · 2020-04-12 03:04

a op= b is a = a op b, and | is the bitwise or operator (bitwise meaning it's applied for each binary digit).

Here is the truth table for or:

    0 1 
    ___
 0| 0 1
 1| 1 1
查看更多
登录 后发表回答