include::../description.adoc[]

include::../how-to-fix-it.adoc[]

This is classically done by using a constant (`constexpr` or `const` if your compiler does not support `constexpr` yet) or an enumeration.
Note that since {cpp}20, some well-known mathematical constants, such as pi, are defined in the header `<numbers>`, and should be preferred over defining your own version (see S6164).

=== Code examples

==== Noncompliant code example

[source,cpp,diff-id=1,diff-type=noncompliant]
----
void doSomething(int var) {
  for (int i = 0; i < 42; i++) { // Noncompliant - 42 is a magic number
    // ...
  }

  if (42 == var) { // Noncompliant - magic number
    // ...
  }
}
----

==== Compliant solution

[source,cpp,diff-id=1,diff-type=compliant]
----
enum Status {
  STATUS_OK = 0,
  STATUS_ERROR = 42
};

void doSomething(Status var) {
  constexpr int maxIterations = 42; // Compliant - in a declaration
  for (int i = 0; i < maxIterations; i++) { // Compliant - 0 is excluded, and maxIterations is a named constant
    // ...
  }

  if (STATUS_OK == var) { // Compliant - number comes from an enum
    // ...
  }
}
----

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
