I wrote this simple helper constexpr
function:
#include <cstdint>
constexpr bool isEven(uint32_t value) { return ((value%2) == 0); }
It is pretty straight forward. I was wondering if this would be considered the most efficient way to determine if some integer value is odd or even? I'm not worried about templating this function for different integral types at the moment. I'm just looking for efficiency and performance while keeping portability in mind.
Edit
To give some context, I might be calling this function within a loop that could iterate 100,000 times to 100,000,000 times or more... So efficiency is key here, but portability is still a factor...
I had thought about "bitwise operations" by checking the least most significant bit as others had stated in their comments or answers, however, I wasn't sure if the compilers would optimize the modulo operator in this context.
Concerning portability, I wasn't sure if "endian" or "integral conventions" would be a leading factor towards which implementation should be used. Considering a system that implements only 1's complement instead of 2's complement, or one that uses Big Endian instead of Little may need to be taken into account.
You can directly use the &
( AND ) operator.
If x
is your int
:
x & 1 // returns 1 if odd, else 0
This is probably the best way to find if an integer is odd or even.