0

I know that OR is an operator for Boolean operands. But when I use it with numbers I get surprising and unexpected results instead of an error. For example:

program test;
uses crt;
begin
clrscr;
writeln(1 or 2);
writeln(2 or 14);
readln;
end.

outputs

3
14

I cannot understand why 1 OR 2 equals 3, and why 2 OR 14 equals 14... Someone explains please.

QA_QC
  • 1
  • 2
    `or` here is acting as a bitwise-or. In binary, 01 or 10 = 11 (3 decimal). 1110 or 10 = 1110 (14 decimal). – EdmCoff May 18 '22 at 18:23

1 Answers1

3

it's acting bitwise-or:

bit      8    7    6    5    4    3    2    1
value  128   64   32   16    8    4    2    1

writeln(1 or 2);

#1:      0    0    0    0    0    0    0    1 = decimal 1
#2:      0    0    0    0    0    0    1    0 = decimal 2
result:  0    0    0    0    0    0    1    1 = decimal 3 = (decimal 1 + decimal 2)
  

writeln(2 or 14);

#1       0    0    0    0    0    0    1    0 = dec 2
#2       0    0    0    0    1    1    1    0 = dec 14 = (decimal 2 + decimal 4 + decimal 8)
result:  0    0    0    0    1    1    1    0 = dec 14

each bit of #1 OR #2