CodeSOD: Busy Busy Busy

One of the common mistakes in a beginner programmer is to wait using a busy loop. Need to pause a program? for(int i = 0; i < SOME_LARGE_NUMBER;i++) continue;

There are a lot of good reasons to not do this, but in microcontroller land, sometimes you actually do want to wait this way. There may be better ways, but there also might not- it depends on your specific constraints.

So, when David S found these lines of C code, it wasn't precisely a WTF.

CheKseg0CacheOn(); for (i=0;i<=SECONDS_1_U;i++) continue; CheKseg0CacheOff();

This disables an optimization on the microcontroller, then busy loops for what should be one second, and then enables that optimization again. This code could be more clear, it could be refactored into a procedure, but this code, on its own, isn't automatically a WTF.

No, the WTF is what happened when the developer responsible needed to wait for three seconds.

if (*SYSSTATUS & System_Reset_Flag) { // CODE THAT DOES SOMETHING } CheKseg0CacheOn(); for (i=0;i<=SECONDS_1_U;i++) continue; CheKseg0CacheOff(); CheKseg0CacheOn(); for (i=0;i<=SECONDS_1_U;i++) continue; CheKseg0CacheOff(); CheKseg0CacheOn(); for (i=0;i<=SECONDS_1_U;i++) continue; CheKseg0CacheOff();

In fact, the only constant for these busy loops was SECONDS_1_U, and all waits were just for one second. No attempt was made to come up with a more general solution that could calculate arbitrary waits, no attempt was made to turn this at least into a procedure for readability, or even a macro. No, it just gets repeated 249 times across 70 different files in the code base.

The developer responsible doesn't work there anymore, but it's fair to say they made their mark.

[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.