Debugging typos

I really want to bang my head against something when I spent an hour debugging a problem again and found it to be a simple typo. For example, I found the problem in the following code (not originally C++ but translated to C it would look like this). It simply should count the numbers of bits set in a value:value = some value where we want to count the number of bits set in it.
testBit = 0x1;
bitsSet = 0;
for (int i=0; i<16; ++i)
{
if (value & testBit)
bitsSet += 1;
testBit << 1;
}
See the problem? Yep, it's the last line. Instead of 'testBit << 1;', it should read 'testBit = testBit << 1;'. Argh. Too bad the compiler didn't write a warning, because that line doesn't actually make sense at all, in any case.
twelve comments, already:
I prefer to always use braces around my conditional and iteration statements. For me it’s easier to read, even though it takes a bit more space.
The compiler may optimize it to the same thing, but why didn’t you use the pre-increment operator on bitsSet like you did with the loop iterator i?
I actually got this as a question during a Google interview: What is the fastest way to count the number of bits set in, for example, an int?
Michael - 06 03 08 - 19:22
Maybe increasing the warning level of your compiler would have helped 
Sylence - 06 03 08 - 19:25
And the utter irony is that a C compiler, with the right options at least, could warn you about that
With a file bug.c
==================================
int main()
{
int value = 10;
int testBit = 0×1;
int bitsSet = 0;
for (int i=0; i
Electron () - 06 03 08 - 19:27
Electron () - 06 03 08 - 19:31
>>>Argh. Too bad the compiler didn’t write a warning
Before you complain about the compiler try to not disable any warnings with pragmas and/or keep your compiler warning level too low:
GCC -Wall produces:
test.cpp:14: warning: statement has no effect
MSVC /W3 (warning level 3) produces:
test.cpp(14) : warning C4552: ‘
BKLA - 06 03 08 - 20:32
MSVC /W3 (warning level 3) produces:
test.cpp(14) : warning C4552: ‘
BKLA - 06 03 08 - 20:33
Petty coding mistakes are those which take the most times to debug. I always end thinking: What, it was just that ?
Hervé () (link) - 07 03 08 - 01:02
Alejo () (link) - 07 03 08 - 01:59
// or
testBit
Joilnen () - 07 03 08 - 15:49
yes, the original language the problem occurred was ActionScript, and that compiler won’t report problems like this :)
niko - 07 03 08 - 15:56
// or
testBit<<=1;
Joilnen () - 07 03 08 - 16:10
There’s a fundamentally different way to count the number of set bits, without using branches. It goes something like this:
value = (value & 0×5555) + ((value & 0xAAAA) >> 1);
value = (value & 0×3333) + ((value & 0xCCCC) >> 2);
value = (value & 0×0F0F) + ((value & 0xF0F0) >> 4);
value = (value & 0×00FF) + ((value & 0xFF00) >> 8);
Depending on the system details (branch overhead etc.), this can be significantly faster. And it looks way cooler, too 
nh - 16 03 08 - 13:35

