Braces! Foiled again!

Just a quick rant, based on how example code from a new compiler I am using is presented.

In C (and similar languages), it is very common to see simple logic presented in one line, such as:

if (AlertLevel == RED) TurnOnSiren();

That is simple to understand, and only takes up one line on the screen or a printout. However, at a previous job, our coding standard forbid that, and always required the use of braces around any actions of an “if”.

if (AlertLevel == RED)
{
   TurnOnSiren();
}

Now, ignoring style preferences of where the braces should go, the use of braces for something like this has some advantages when it comes to preventing potential bugs if this code is changed in the future.

In the case of the compiler examples I have been seeing, they show them without braces, such as:

if (AlertLevel == RED)
   TurnOnSiren();

For simple and short logic, this is no different than my first example — it just places the “what to do” stuff on an indented line after the “if”.

However, a common bug I see occurs when someone expands upon that like this:

if (AlertLevel == RED)
   TurnOnSiren();
   FlashRedLight();

In some languages, where program flow is determined by indentation, this would work. But in C, indentation does not matter. The above code would actually be processed as:

if (AlertLevel == RED) TurnOnSiren();

FlashRedLight();

The red lights would flash every time through, regardless of the status of AlertLevel.

Unintended consequences of not using braces, and using indents to format each statement on its own line.

By always using braces (even on simple one-statement things like this example), you avoid that:

if (AlertLevel == RED)
{
   TurnOnSiren();
   FlashRedLight();
}

Now we have the desired result, as adding new code or function calls inside the braces will work as we intended.

It’s 2019. The C Programming Language came out 47 years ago, and I still occasionally run into bugs caused by the lack of braces.

Thanks to a former job, I no longer make this mistake. I always use braces.

This has been a public service announcement of Sub-Etha Software.

Leave a Reply

Your email address will not be published. Required fields are marked *