Avoid macros defining constants

Avoid macros defining constants

Software ResiliencyCode Reliability
This code insight verifies in C++ applications when macros without parameters define a literal constant. Depending on the density of occurrences and the thresholds set for this code insight, Highlight counts penalty points for the scanned file.

Literal constants are numbers, characters or strings (numbers, possibly preceded with . or \, characters enclosed with ‘, strings, enclosed with ‘ or “).

Why you should care

As macros do not obey the C++ scope and type rules, this often leads to subtle and not-so-subtle problems, causing unexpected behaviors or compilation issues.

CAST recommendations

C++ provides alternatives that fit better than macros with the rest of C++, such as inline functions, templates, and namespaces. As a C++ developer mentioned on StackOverflow “you should stop using Macros (at least to define constants) whenever you can. Macros are wild things against namespaces and scopes. On the other hand const objects have type and this can reduce unintended mistakes.

References

http://www.stroustrup.com/bs_faq2.html#macro
https://blogs.msdn.microsoft.com/doronh/2006/03/27/avoiding-defines-for-constant-data-and-using-enums-instead/
https://stackoverflow.com/questions/19615851/in-c-is-it-better-to-use-define-or-const-to-avoid-magic-numbers

 

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.

How it worksFeatures & Analytics