How much is the {…}?
[by Dr. Daniel Simon, Head of Professional Services at Axivion]
If you work on a software project with safety and/or security background, you will have to use some sort of programming guide. In automotive industry, MISRA and Autosar C++14 standards are widely used, and therefore other industries also take these standards as a starting point for defining best practise rules.
When you are not “forced” to comply with a certain safety standard but still want to use a programming guide for aligning the “style” of programming in your teams, it is a good idea to discuss the rules to be followed with your team upfront.
Two of the rules I strongly recommend developers to follow are
- “Expressions resulting from the expansion of macro parameters shall be enclosed in parentheses” (e.g., Misra C:2012, R 20.7) and
- “Complete use of curly braces to indicate block structure in code” (e.g. Misra C++:2008, Rule 6.4.1 and other, also known as Autorsar C++14 Rule M6.4.1).
For (1), we have the obvious bad example of
and an implementation file
The second use is different from square as a C function and results in surprising values for i at runtime. Happy debugging.
Note that even though naming conventions (“write macros in UPPERCASE”) would be an improvement here,
they do not solve the issue completely.
For (2), consider
Here, the then branch of the if statement will call a function under some condition. Your tests show: it works.
Two weeks later, a colleague changes a header file for a completely unrelated task and your system breaks.
Sometimes, at least. What’s happend?
The changed header file now contains a new macro definition like
which – by coincidence – breaks your code without so much as touching it.
Again, we are stepping through this code in a debugger… what do you see in the iteration? Happy debugging again.
So let’s estimate:
- How much time does it take to add parentheses/braces when writing the code? (almost no time)
- How much time does it take to debug the obscure errors? (depends… minutes to hours)
- How many parentheses/braces can you add to your code instead of debugging? (left to the reader)
If you would like to find out more about Axivion, Axivion Coding Guidelines or our Axivion Suite please follow the links or contact us directly via Chat, contactform or by Email. We´re looking forward hearing from you!