Dave's Brain

Browse - programming tips - c isodd iseven

Date: 2008jan17
Language: C/C++
Level: Beginner

Q.  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;
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.