Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Magic number (programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Accepted uses {{anchor|Accepted limited use of magic numbers}} === {{More citations needed section|date=March 2010}} In some contexts, the use of unnamed numerical constants is generally accepted (and arguably "not magic"). While such acceptance is subjective, and often depends on individual coding habits, the following are common examples: * the use of 0 and 1 as initial or incremental values in a [[for loop]], such as {{code|2=cpp|1=for (int i = 0; i < max; i += 1)}} * the use of 2 to check whether a number is even or odd, as in <code>isEven = (x % 2 == 0)</code>, where <code>%</code> is the [[modulo]] operator * the use of simple arithmetic constants, e.g., in expressions such as <code>circumference = 2 * Math.PI * radius</code>,<ref name="MartinG25"/> or for calculating the [[discriminant]] of a [[quadratic equation]] as <code>d = b^2 β 4*a*c</code> * the use of powers of 10 to convert metric values (e.g. between grams and kilograms) or to calculate percentage and [[per mille]] values * exponents in expressions such as <code>(f(x) ** 2 + f(y) ** 2) ** 0.5</code> for <math>\sqrt{f(x)^2 + f(y)^2}</math> The constants 1 and 0 are sometimes used to represent the [[Boolean data type|Boolean]] values true and false in programming languages without a Boolean type, such as older versions of [[C (programming language)|C]]. Most modern programming languages provide a <code>boolean</code> or <code>bool</code> [[primitive type]] and so the use of 0 and 1 is ill-advised. This can be more confusing since 0 sometimes means programmatic success (when -1 means failure) and failure in other cases (when 1 means success). In C and C++, 0 represents the [[null pointer]]. As with Boolean values, the C standard library includes a macro definition <code>NULL</code> whose use is encouraged. Other languages provide a specific <code>null</code> or <code>nil</code> value and when this is the case no alternative should be used. The typed pointer constant <code>nullptr</code> has been introduced with C++11.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)