The problem isn't your code. There is a 2012 bug report on this issue in Google Code.
Once you start getting bitten by the non-standard behavior of the Arduino IDE, you've outgrown it and the only real remedy is to move up to real tools that work as you'd expect. A few of the choices include:
Eclipse is a good one,choice; it can take a little patience and searching to get it set up right, but once you do it's a solid development environment you can stay with for a long time. It runs everywhere Java doesdoes.
AVR makes an IDE that seems to have a good reputation, it'sAtmel Studio is well thought of. It's proprietary ($), not free [?], and only for windows.
Apple's Xcode can be configured to use the avr-gcc toolset. It's(Even thought it's right here on my system but, I'm happy with Eclipse and haven't tried it).
Likewise, you can use Microsoft Visual Studio (the linked article is just one of mamymany).
Command line: You can get down and dirty with your favorite editor, the gcc toolset for AVR, and bang away at your keyboard. Not sexy, but you'll learn everything that's going on between your code the board.