Bit By Byte

Quick, what’s wrong with this code?

Looks good, right? Well this innocent looking routine caused Eclipse to go rampant and brought my MacBook to it’s knees, twice. I had to lean on the power button both times.

I stared and stared at this code and finally started stepping through it in the debugger! It appeared that both loops were working fine, but that a was never incrementing. It just stayed at -128 while b incremented and wrapped around again and again, infinitely...

Have you spotted the problem yet?

The problem is, neither of the loops can terminate. Neither for condition will ever become false and cause the loop to terminate, because neither a nor b can ever grow larger than Byte.MAX_VALUE. Of course! >Audible forehead slap.<

Feeling rather sheepish, I replaced the above code with this:

I pondered whether this would be a good fit for the elusive do...while construct, but I'm a lazy lazy man.

7 Comments

  1. Jay Meyer:

    Would you instead just replace the a

  2. Jay Meyer:

    Would you instead just replace the a”

  3. Jay Meyer:

    seems you have html parsing enabled so I cannot type the “greater-Than” symbol into you comments.

    Would you instead just replace the “a greater-than=” with “a greater-than” ? It appears that would work (but I would debug it, first). Seems like that is much easier and more readable than those hideous break statements.

  4. Scott:

    Sorry, I’ll see if I can disable html parsing.

    You mean replace ‘a <=’ with ‘a <’? The problem there is, I need the loop bodies to execute when a or b are Byte.MAX_VALUE (127). If I use your suggestion the loops will indeed terminate, but too early for me.

    I agree it’s gross looking, it’s just one of those funny corner cases that 99 other times out of 100 can be written the first way I tried it without any problems. Thanks for the suggestion, though – I actually did try it just now in Eclipse.

  5. Alex Miller:

    Oops, sorry man. I set you up with that test code. :)

    BTW, you can always do “&>” for > in html comments.

  6. Alex Miller:

    Sorry that’s “& g t ;”

  7. Jay Meyer:

    oh I see now! 127++ == -128. Those cursed Java primitives roll their value instead of throwing an exception – ah, well.. maybe Java 7 can fix that ;) (for it is written that Java 7 is a panacea to clobber Python, Ruby, and Groovy for good!) I didn’t see that until I ran a test case today. In fact I also tried it with java.lang.Byte mixed with Integers yet new Byte(128).byteValue() = -128 – instead of throwing and exception like I expected. So I can’t find a more succinct solution than you did, except replacing the for loop with a while{if.. break) combo similar to your anyway. good find.

Leave a comment