The Operator ||
is the "or" operator for logical operations ("boolean" or "bulian"):
if(foo == 'a' || foo == 'b')
Is the same as saying foo = a
or foo = b
, that is, any of the results being true, the condition is met.
Already the operator |
is the "OR binary", it merges the bits of the parameters in this way:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
The logic is the same as ||
(either side being true results in true), but applies to the individual bits of each of the parameters. As an example, 3 | 5
results in 7
, for 3
is 0011
in binary, and 5
is 0101
:
0011
| 0101
= 0111
Note that in this case, the operation performed leaves a numerical result, because we are working with the values, and not with a mere true or false "generalized", as in the case of ||
.
Usually the flags of a program are usually defined as constant:
#define FLAG1 0x0001 // equivale a 0001 em binário
#define FLAG2 0x0002 // equivale a 0010 em binário
#define FLAG3 0x0004 // equivale a 0100 em binário
#define FLAG3 0x0008 // equivale a 1000 em binário
just when you make a ( FLAG1 | FLAG3 )
have an unambiguous result:
FLAG1 | FLAG3
results in 5
in the given example, no other combination gives this.
You may find good material in the Java specification.
– Cold
@Can Renang post more details of the practical case? Are strings really the constants? The | can also be used in regex, would be cool if you contextualize better, because I gave a more general response. In other words, if it’s exactly the way you put it in the example, theoretically it can’t work. Maybe in an extreme case, if it was a number instead of bar, but even so it is a little strange the example.
– Bacco
In fact, according to the specification the binary OR only applies to integers (or types that can be implicitly converted to integers) or booleans (in which case it behaves just like the logical OR). Use with strings should produce a
error: bad operand types for binary operator '|'
.– mgibsonbr
I was going to say it’s easy to find material, but the official material really is very laconic. Good question.
– Oralista de Sistemas