How to Use Bitwise OR Operator in C: Syntax and Examples
In C, the bitwise OR operator is
|. It compares each bit of two integers and returns a new integer where each bit is 1 if either bit of the operands is 1. Use it like result = a | b; to combine bits from a and b.Syntax
The bitwise OR operator in C is written as |. It takes two integer operands and compares their bits one by one.
- Operand 1: First integer value.
- Operand 2: Second integer value.
- Result: Integer with bits set to 1 where either operand has a 1 bit.
c
result = operand1 | operand2;
Example
This example shows how to use the bitwise OR operator to combine bits of two numbers and print the result.
c
#include <stdio.h> int main() { int a = 5; // binary: 0101 int b = 9; // binary: 1001 int result = a | b; // bitwise OR printf("a = %d, b = %d\n", a, b); printf("a | b = %d\n", result); // expected 13 (binary 1101) return 0; }
Output
a = 5, b = 9
a | b = 13
Common Pitfalls
Common mistakes when using bitwise OR include:
- Using
|instead of logical OR||when testing conditions. - Applying bitwise OR to non-integer types without casting.
- Expecting decimal addition instead of bitwise combination.
Remember, | works on bits, not whole numbers as sums.
c
#include <stdio.h> int main() { int x = 2; // binary 0010 int y = 4; // binary 0100 // Wrong: using bitwise OR instead of logical OR int wrong = x | y; // result is 6 (binary 0110) // Correct: logical OR int correct = x || y; // result is 1 (true) printf("Bitwise OR result: %d\n", wrong); printf("Logical OR result: %d\n", correct); return 0; }
Output
Bitwise OR result: 6
Logical OR result: 1
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| | | Bitwise OR | 5 | 9 | 13 (binary 1101) |
| || | Logical OR (not bitwise) | 5 || 9 | 1 (true) |
Key Takeaways
Use the bitwise OR operator
| to combine bits of two integers.Bitwise OR sets each bit to 1 if either operand has a 1 bit in that position.
Do not confuse bitwise OR
| with logical OR ||.Bitwise OR works only on integer types and their bits.
Check your operands to avoid unexpected results from mixing logical and bitwise operators.