The short answer
In C, || is the logical OR operator. It combines two conditions. The result is 1 (true) when at least one side is true, and 0 (false) when both sides are false. C++ has the same operator, but its result has type bool.
A simple example
#include <stdio.h>
int main(void) {
int age = 16;
int has_permission = 1;
if (age >= 18 || has_permission) {
printf("Access granted\n");
}
return 0;
}
The left side, age >= 18, is false. The right side, has_permission, is 1, which counts as true. One true side is enough, so the message prints.
Truth table
| Left side | Right side | Result |
|---|---|---|
| 0 (false) | 0 (false) | 0 |
| 0 (false) | nonzero (true) | 1 |
| nonzero (true) | 0 (false) | 1 |
| nonzero (true) | nonzero (true) | 1 |
Any nonzero value counts as true in C. The result of || is always 1 or 0, so 5 || 0 gives 1, not 5.
Short-circuit evaluation
If the left side is true, C does not evaluate the right side. This matters when the right side could fail:
#include <stdio.h>
int main(void) {
int *p = NULL;
if (p == NULL || *p == 0) {
printf("The pointer is NULL, so *p was never read\n");
}
return 0;
}
p == NULL is true, so C skips *p == 0. Reading through a NULL pointer is undefined behavior, so the order of the two sides matters. Swapping them would read through the NULL pointer first.
Using || with comparisons
|| often combines comparisons. This check flags a value that falls outside the range 0 to 100:
if (score < 0 || score > 100) {
printf("Score out of range\n");
}
&& binds more tightly than ||, so a || b && c means a || (b && c). Add parentheses when you mix the two, so the intent is clear.
Not the same as |
The single | is a different operator. It works on the bits of integers, and it always evaluates both sides. In the null pointer example, (p == NULL) | (*p == 0) would still read *p when p is NULL. For how | works on bits, see bitwise xor c.
The ! operator flips a condition, and unary operators in c explains how it fits with the other operators.