# Checking if integer is even or not

This topic is 4454 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Helo. I want to check if an integer is even number or not. Is there any safer and faster code than this:
static inline bool CHECKEVEN(int num)
{
return (num/2 == (float)num/2.0f) ? true : false;
}



##### Share on other sites
You should only post one post.

Anyway you can use the modulus operator (like the remainder you most likely have learned in school), so 5%3 = 2 because the remainder is two. So N%2 == 1 for odd and N%2 == 0 for even.

return (N%2==0);

Or if you for some reason prefer the ternary operator:

return ((N%2==0)?true:false);

Σnigma

##### Share on other sites
Thank you for your fast reply [smile]. I deleted my first post. I'm accidentaly clicked on refersh button and posted it twice.

##### Share on other sites
Instead of using a costly modulo oparation, you'd rather check the LSB (least significant bit) with a simple AND. If the result is zero, the number is even.
static inline bool CHECKEVEN(int num){	return ((num & 1} == 0);}

##### Share on other sites
Yeah this is very nice [smile] I tried 6 or 7 examples but these are the fastes:

static inline bool CHECKEVEN(int x){
return ((x/2)*2 == x);
}

static inline bool CHECKEVEN(int x){
return ((x&1)==0);
}

for now....

##### Share on other sites
Quote:
 Original post by streamerYeah this is very nice [smile] I tried 6 or 7 examples but these are the fastes:static inline bool CHECKEVEN(int x){ return ((x/2)*2 == x);}static inline bool CHECKEVEN(int x){ return ((x&1)==0);}for now....
I don't know if this is standard, but in my experience all caps is usually reserved for macros, enums, and constants. I just mention it because it might make calls to the above functions look a little misleading.

##### Share on other sites
It is not standard, but everybody use caps for macros. I'm using too. Firstly this was a macro, and after one year of developing my 'little' program has a bunch of CHECKEVEN calls. And then I turned my macro to proc, and I'm too lazy to rename all calls [smile]

##### Share on other sites
Quote:
 Original post by streamer...and I'm too lazy to rename all calls [smile]
Does your IDE have a 'search and replace' feature? :-)

##### Share on other sites
yup [smile]
But I used to this function. I love it with caps, and I can't hurt that little proc.

It is with caps mainly because of one reason. I can spot it very fastly when I search throught the code:

if(CHECKEVEN(player.x)) ....

• 10
• 16
• 9
• 13
• 41