The operator ||
is the "or" operator for logical operations ("boolean" or "bulianas"):
if(foo == 'a' || foo == 'b')
It is the same as saying foo = a
or foo = b
, that is, any of the results being true, the condition is satisfied.
Now the |
operator is the "binary OU", it merges the bits of the parameters like this:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
The logic is the same as ||
(either side being true, it results in true), but it applies to the individual bits of each of the parameters. As an example, 3 | 5
results in 7
, since 3
is 0011
in binary, and 5
is 0101
:
0011
| 0101
= 0111
Note that in this case, the operation performed leaves a numeric result, since we are working with the values, not with a mere "true" or false "generalized", as in the case of ||
.
Normally the flags of a program are usually defined as constants like this:
#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.