| operator against || operator

A simple question, but what does the operator do | unlike the operator || (or)?

+6
c operators
source share
5 answers

| is the bitwise OR operator, where as || is a logical OR operator. Namely, the former is used to “combine” bits from two numerical values ​​as a union, while the latter evaluates to true if either the condition on the left or right side of the operator is true.

In particular, bitwise operators ( not that should be confused with logical operators) work on each bit of numbers (in the same ordinal position) and accordingly calculate the result. In the case of bitwise OR resulting bit is 1 if the bit is 1, and 0 only if both bits are 0. For example, 1 | 2 = 3 because:

 1 = 0001 2 = 0010 -------- 0011 = 3 

In addition, 2 | 3 = 3 because:

 2 = 0010 3 = 0011 -------- 0011 = 3 

This may seem confusing at first, but in the end you will get it. A bitwise OR used in most cases to set flags in a bitfield. That is, a value containing an on / off state for a set of related conditions in a single value (usually a 32-bit number). In Win32, a window style value is a good example of a bit field, where each style is represented by a single bit (or flag), for example WS_CAPTION, which indicates whether the window has a title bar.

+11
source share

There are several (usually 32, 16, 8 or 64) bits in a word. Bitwise OR (one vertical bar) returns a logical OR for each bit position at that bit position. Logical OR (two vertical stripes) returns TRUE or FALSE.

+3
source share

| is a bitwise or operator. Wikipedia page Operators in C and C ++ describe all operators well.

+2
source share

As others noted, | is a bitwise OR operator, and || is an OR logical operator, and they represent conceptually different operations that (as a rule) work on different types of inputs. But then another question may arise: if you used | with boolean operands, will this not do the same as || since everything ultimately comes down to bits? Do I need a separate operator || ?

Besides the fundamental difference, another important difference is that || is short-circuited. This means that if the first operand is true, the second operand is not evaluated at all. For example:

 int flag = Foo() || Bar(); 

will only call Bar() if Foo() returns 0. If used | Both operands have always been evaluated.

(And, of course, & and && have similar behavior.)

+2
source share

|| is logical and / is bitwise or. In most cases, when you check things like if (i == 0 || i == 1), you just want to use || but when you do something like passing flags as a variable use |. (If you don't know what you probably don't need at all)

0
source share

All Articles