开发者

| operator versus || operator

开发者 https://www.devze.com 2023-01-14 06:29 出处:网络
Simple question but w开发者_Go百科hat does the | operator do as opposed to the || (or) operator?| is a bitwise OR operator, where as || is a logical OR operator. Namely, the former is used to \"combin

Simple question but w开发者_Go百科hat does the | operator do as opposed to the || (or) operator?


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

Specifically, bitwise operators (not to be confused with logical operators) operate on each bit of the numbers (at the same ordinal position), and calculates a result accordingly. In the case of a bitwise OR, the resulting bit is 1 if either bit is 1, and 0 only if both bits are 0. For example, 1|2 = 3, because:

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

Furthermore, 2|3 = 3, because:

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

This can seem confusing at first, but eventually you get the hang of it. Bitwise OR is used mostly in cases to set flags on a bit field. That is, a value holding the on/off state for a set of related conditions in a single value (usually a 32 bit number). In Win32, the window style value is a good example of a bit field, where each style is represented by a single bit (or flag), like WS_CAPTION, which indicates whether or not the window has a title bar.


There are several (usually 32, 16, 8 or 64) bits in a word. The bitwise OR (one vertical bar) returns the logical OR for each bit postion in that bit position. The logical OR (two vertical bars) only returns TRUE or FALSE.


| is the bitwise or operator. The wikipedia page Operators in C and C++ describes all of the operators pretty well.


As others have mentioned, | is the bitwise OR operator and || is the logical OR operator, and they are conceptually different operations that (usually) operate on different sorts of inputs. But this then might raise another question: if you used | with boolean operands, wouldn't that do the same thing as || since everything ultimately boils down to bits anyway? Is a distinct || operator necessary?

Aside from the conceptual difference, another important difference is that || is short-circuiting. This means that if the first operand is true, the second operand isn't evaluated at all. For example:

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

would invoke Bar() only if Foo() returns 0. If | were used, both operands always would be evaluated.

(And, of course, & and && have analogous behaviors.)


The || is a logical or and the | is a bitwise or. Most of the time when you are checking things like if (i == 0 || i ==1) you just want to use || but when you are doing things like passing flags as a variable use |. (If you don't know what that is you probably don't need | at all)

0

精彩评论

暂无评论...
验证码 换一张
取 消