Logical OR Operator

The logical OR operator is '||'

The result of the logical OR operator is 1 if either arguments are logical TRUE and it is 0 if both of its arguments are logical FALSE

logical TRUE is defined as any non-zero value
logical FALSE is defined as the value zero

Put this another way, the result of the logical OR operator is 1 if either argument is not 0 and it is 0 if both of its arguments are 0

If we call the inputs A and B and the output C we can show the logical OR function as:

A B C
FALSE  ||  FALSE -> FALSE
FALSE  ||  TRUE -> TRUE
TRUE  ||  FALSE -> TRUE
TRUE  ||  TRUE -> TRUE
The binary OR function operates on all bits in parallel (see binary OR for more details)
A   B   C
0  |  0 -> 0
0  |  1 -> 1
1  |  0 -> 1
1  |  1 -> 1
Logical OR and binary OR differ subtlely.

With locical OR, 0x02 is logical TRUE and 0x04 is also logical TRUE

so  (0x02  ||  0x04)  results in  0x01  which is logical TRUE

whereas  (0x02  |  0x04)  results in  0x06  which is also logical TRUE but a different logical TRUE

Detailed Truth Tables

binary

  logical

  logical

A   B   C         A   B   C         A   B   C
0  |  0 -> 0         0  ||  0 -> 0         FALSE  ||  FALSE -> FALSE
0  |  1 -> 1         0  ||  1 -> 1         FALSE  ||  TRUE -> TRUE
1  |  0 -> 1         1  ||  0 -> 1         TRUE  ||  FALSE -> TRUE
1  |  1 -> 1         1  ||  1 -> 1         TRUE  ||  TRUE -> TRUE
binary

  logical

  logical

A   B   C         A   B   C         A   B   C
0x00  |  0x00 -> 0x00         0x00  ||  0x00 -> 0x00         FALSE  ||  FALSE -> FALSE
0x00  |  0x04 -> 0x04         0x00  ||  0x04 -> 0x01         TRUE  ||  TRUE -> TRUE
0x02  |  0x00 -> 0x02         0x02  ||  0x00 -> 0x01         TRUE  ||  TRUE -> TRUE
0x02  |  0x04 -> 0x06         0x02  ||  0x04 -> 0x01         TRUE  ||  TRUE -> TRUE

Early Out Operator

The logical OR operator is an early out operator. This means that as soon as the result is known, the remainder of the expression is ignored.

How is this possible? It is possible because if the first argument evaluates to TRUE then no mater what value the second argument has the result will always be TRUE

NOTE: the binary OR operator is NOT an early out operator

Common use of logical OR operator

The logical OR is normally used in conditional expressions such as if and while statements

e.g.

	if  X == 2  then
		// execute these statements if X is equal to 2
		j = j + X
	else

		if  X == 3  then
			// execute these statements if X is equal to 3
			j = j + X
		else

			if  X == 5  then
				// execute these statements if X is equal to 5
				j = j + X
			endif
		endif
	endif
is equivalent to
	if  X == 2  ||  X == 3  ||  X == 5  then
		// execute these statements if
		//	X is equal to 2 OR
		//	X is equal to 3 OR
		//	X is equal to 5
		j = j + X
	endif

The use of logical OR makes the second piece of code easier to understand and more efficient.