David Merposa wrote:
> Hello,
>
> We have some code that runs on Linux and Windows. The code uses a ring
> buffer. To "increment" the index of the ring buffer, the following
> construct is used:
>
> index = ++index % N;
>
> We recently had a review of this code, and my co-worker Tony and I
> pointed out to the guy who wrote this code--Sporty--that it is undefined
> behavior. The code currently "works" on both Linux and Windows, so he
> told us that if it works, don't fix it.
Fix it. Even if it happens to do what's desired (just by
chance), you're at the mercy of the compiler's whim. Install
a new compiler version, or change the optimization level, or
even just add an innocent-looking printf() twelve lines earlier,
and all bets are off.
Remember how those silent-movie villains would tie helpless
damsels to the railroad tracks? The "nothing bad has happened
yet" viewpoint calls for leaving the damsel where she is until
after the train rolls over her.
> While we agree with Sporty that it currently "works" on both Linux and
> Windows, we're a bit concerned that it may not "work" in the future.
> Sporty is like an old dog, and it is difficult if not impossible to
> teach him "new tricks".
I've not met your Sporty, but I'll take a guess that I'm
an even older dog than he is. But I'm still capable of learning
from experience (especially from bad experience), and you won't
find *me* sniffing at the intake end of the running snow-blower,
no, never again!
--
Eric Sosman
lid