isocpp / isocpp/CppCoreGuidelines

ES.45 - Magic numbers in math operations

Open
#1,861 31 comments 2 reactions 1 assignee View on GitHub

@hsutter is already working on this.

Since Jan 27, 2022.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

Hi!

I have a question about ES.45. The way it's written, it bans any use of magic numbers (except a positive list of exceptions for the most common numbers, like 0, 1, etc). While I think the rule makes complete sense and I fully agree with the provided example, I believe it's detrimental when writing code that implements math, for example implementing a scientific paper in code:

// From paper X, Equation 2)
double x = 0.123 * y + 0.456 * z + 0.5 * w;

Versus:

// From paper X, Equation 2)
double x = kConstant0123 * y + kConstant0456 * z + kHalf * w;

Readability is greatly reduced in this case, plus makes reviewing the code much harder. The code is easier to review if it visually looks as similar as possible to the original source in the paper.

A solution is to add these magic constants to a list of "accepted" magic constants, but it feels that list can easily grow and defeat the purpose.

What do you think? Would it make sense to document this use case and offer some sensible advice?

Thanks!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.