static inline bool CHECKEVEN(int num)
{
return (num/2 == (float)num/2.0f) ? true : false;
}
Checking if integer is even or not
Helo.
I want to check if an integer is even number or not.
Is there any safer and faster code than this:
Thanks in advance
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);
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);
Thank you for your fast reply [smile]. I deleted my first post. I'm accidentaly clicked on refersh button and posted it twice.
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.
Edit: missed the link that already shows this.
static inline bool CHECKEVEN(int num){ return ((num & 1} == 0);}
Edit: missed the link that already shows this.
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....
static inline bool CHECKEVEN(int x){
return ((x/2)*2 == x);
}
static inline bool CHECKEVEN(int x){
return ((x&1)==0);
}
for now....
Quote:Original post by streamerI 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.
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....
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]
Quote:Original post by streamerDoes your IDE have a 'search and replace' feature? :-)
...and I'm too lazy to rename all calls [smile]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement