Should I prefer +
(addition) operator or |
(or) operator if both would give the same result?
I understand that addition and logical OR are different things. But they sometimes do the same thing in some macros, especially when playing with bytes and bits. Which one should I prefer in this case?
Example:
uint8_t Byte1 = 0x02; // 0000 0010
uint8_t Byte2 = 0x80; // 1000 0000
uint16_t Word1, Word2; // 0000 0010 1000 0000 = 640 = 0x0280
Word1 = (Byte1 << 8) + Byte2;
Word2 = (Byte1 << 8) | Byte2;
std::cout << "Word1 = " << Word1 << std::endl;
std::cout << "Word2 = " << Word2 << std::endl;
Output:
Word1 = 640
Word2 = 640
When manipulating bit patterns, logical operators are appropriate. When manipulating numeric values, arithmetic operators are appropriate.