Well, there are at least two low-level ways of determining whether a given number is even or not:
1. if (num%2 == 0) { /* even */ }
2. if ((num&1) == 0) { /* even */ }
I consider the second option to be far more elegant and meaningful, and that’s the one I usually use. But it is not only a matter of taste; The actual performance may vary: usually the bitwise operations (such as the logial-and here) are far more efficient than a mod (or div) operation. Of course, you may argue that some compilers will be able to optimize it anyway, and I agree…but some won’t.
Another point is that the second one might be a little harder to comprehend for less experienced programmers. On that I’d answer that it will probably only benefit everybody if these programmers take that short time to understand statements of this kind.
What do you think?
The given two snippets are correct only if num is either an unsigned int, or a negative number with a two’s complement representation. – As some comments righfuly state.
If you’re going to say that some compilers won’t optimise
%2, then you should also note that some compilers use a ones’ complement representation for signed integers. In that representation,&1gives the wrong answer for negative numbers.So what do you want – code which is slow on “some compilers”, or code which is wrong on “some compilers”? Not necessarily the same compilers in each case, but both kinds are extremely rare.
Of course if
numis of an unsigned type, or one of the C99 fixed-width integer types (int8_tand so on, which are required to be 2’s complement), then this isn’t an issue. In that case, I consider%2to be more elegant and meaningful, and&1to be a hack that might conceivably be necessary sometimes for performance. I think for example that CPython doesn’t do this optimisation, and the same will be true of fully interpreted languages (although then the parsing overhead likely dwarfs the difference between the two machine instructions). I’d be a bit surprised to come across a C or C++ compiler that didn’t do it where possible, though, because it’s a no-brainer at the point of emitting instructions if not before.In general, I would say that in C++ you are completely at the mercy of the compiler’s ability to optimise. Standard containers and algorithms have n levels of indirection, most of which disappears when the compiler has finished inlining and optimising. A decent C++ compiler can handle arithmetic with constant values before breakfast, and a non-decent C++ compiler will produce rubbish code no matter what you do.