Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

| operator versus || operator

Tags:

c

operators

Simple question but what does the | operator do as opposed to the || (or) operator?

like image 949
NoodleOfDeath Avatar asked Sep 05 '10 03:09

NoodleOfDeath


People also ask

What is the difference between and || operator?

Differences between | and || operators in Java| is a bitwise operator and compares each operands bitwise. It is a binary OR Operator and copies a bit to the result it exists in either operands. (A | B) will give 61 which is 0011 1101. Whereas || is a logical OR operator and operates on boolean operands.

What does the || operator do?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

What is the difference between and || in JS?

In short, the difference between the two operators boils down to the difference between falsy and null/undefined . Where the logical or ( || ) operator takes the right operand in the case of a falsy value — which includes empty string, 0, false, NaN, etc.

What is the difference between operator && and || in C++?

In C++ (and a few other languages) && and || are your logical operators in conditions. && is the logical AND operator and || is the logical OR operator.


2 Answers

| 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.

like image 156
Javert93 Avatar answered Nov 10 '22 16:11

Javert93


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.

like image 40
hotpaw2 Avatar answered Nov 10 '22 18:11

hotpaw2