Answer to the C Puzzle

Solution
Image by Gino Crescoli from Pixabay

If you look back at the puzzle, you might think the for loop is a bit odd starting at -1 and that’s the snag. It exits the for loop immediately because -1 is actually more than 5. It’s a rather subtle bug. The type of d is obviously int, but the type of (TOTAL_ELEMENTS – 2) is unsigned int.

So what I believe is happening is the compiler is promoting d to an unsigned int which is 4294967295, and clearly that’s a bit larger than 5. To fix this just put (int) before the (TOTAL_ELEMENTS – 2) in the for loop and it will work.

(Visited 59 times, 1 visits today)