Programming Tips - C/C++: What's the nicest way to test if a number is odd or even in C/C++ ?

Date: 2008jan17 Update: 2026sep16 Language: C/C++ Level: novice Q. C/C++: What's the nicest way to test if a number is odd or even in C/C++ ? A. I think this pair of functions is about as nice as you can get:
inline bool isOdd(const int n) { return n % 2; }
inline bool isEven(const int n) { return ! isOdd(n); }
// Here's another approach looking at the low order bit. // May not work with negative numbers. inline bool isOdd(const int n) { return n & 1; }
Example Use:
#include <stdio.h> void main() { for (int i = 0; i < 10; i++) { if (isOdd(i)) { printf("i=%d is odd\n", i); } else { printf("i=%d is even\n", i); } } }
Outputs:
i=0 is even i=1 is odd i=2 is even i=3 is odd i=4 is even i=5 is odd i=6 is even i=7 is odd i=8 is even i=9 is odd