C/S109: Magic Number Exceptions for Floats

Hi all, I’ve noticed recently that floating point numbers have been triggering magic number violations in my codebase, as a result of a ticket made from this conversation:

C++ / S109: Magic number in initialization list

I was wondering if it would be possible to make exceptions for some floating point values as with integers, such as 0.0F (for clearing variables that hold running averages, etc.) and maybe some others that could be relevant. Not sure if the weirdness of floating point math makes this tricker than it seems initially. Thanks!

Hi Josh,

Thanks for the report. Floating-point literals actually weren’t covered by S109 at all until a recent change which both fixed that gap and, separately, extended the integer exception list to allow 0, 1, 2, and 3 as “not magic.” That second part wasn’t mirrored for floats, so something like 0.0F now gets flagged with no equivalent exception, even though the integer 0 is allowed.

That was an intentional asymmetry based on the data we had, but we are happy to revisit it based on your feedback. I’ve raised the issue internally proposing to extend the same allowed-value exceptions to floating-point literals. I don’t have a timeline now, but I will come back here next week to share whatever updates I have with you.

In the meantime, the usual workaround applies: assign the value to a well-named constant/variable (e.g. constexpr float kResetValue = 0.0F;).

Hi Josh,

The fix for this issue should be available in the next release version of our plugin. Target date for the release is September 10.