Since I've only programmed in C++ rather than C for a long time and I'm not
familiar with the C standard, I'd like to know if the function below is
guaranteed to work (including for negative numbers). I suspect that it
isn't, but I'd like to make sure:
int isEven(int n)
{
if((n & 1) == 1)
return 0;
else
return 1;
}
DW
No, it is most emphatically not guaranteed to work, not in C and not
in C++. C++ adopted C's three allowed representations for signed
integer types (they call it "inherited", we call it "misappropriated",
go figure).
This will work in any C or C++ implementation for unsigned integer
types. This will work in any C or C++ implementation for any signed
integer type with a positive value. But when you get to signed
integer types with a negative value...
It works for 2's complement. It works for signed magnitude. It is
wrong every single time for 1's complement, with the possible
exception of -0, if the implementation allows -0.
In general, I never worry about non 2's complement implementations.
Really, try and find one. But I wouldn't code it this way, anyway. It
has been at least 10 years since I have seen a compiler brain-dead
enough to not replace a division or modulo by a power of 2.
I would write it:
int isEven(int n)
{
return !(n % 2);
}
The fact that this would also work correctly on 1's complement
implementations, if I ever trip over one, is an extremely small
additional bonus.