Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) magic constant

 

A magic constant is the use of a literal without mentioning where that literal came from.

 

For example, in the code below, 12 is a magic constant that occurs twice. How is this 12 determined? Is it the number of notes per chord, or is it a dozen? And if the upper 12 is changed, must the lower 12 be changed as well?

 

int main()
{
  for (int i=0; i!=12; ++i)
  {
    //
  }
  for (int i=0; i!=12; ++i)
  {
    //
  }
}

 

 

 

 

 

Advice

 

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 6.6. Advice. page 169: '[6] Avoid "magic constants"'
  2. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 10.6. Advice. page 271: '[6] Define symbolic constants to avoid "magic constants"'
  3. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 17: 'Avoid magic numbers'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict