I have forgotten

• https://me.yahoo.com

# Gotcha #2: Magic Numbers

6 Nov 07, 11:02AM
Gotcha #2: Magic Numbers
As a general rule is not good to use a raw numerical literal is situations where a named constant should be used instead. For example, the following code is poor:
`for(int i=0;i<10;i++) { /* ... */ }`

While there is nothing wrong with the actual code, the first question that any other developer is going to ask is 'why 10'? The second question may be 'can I change this number to 15?' (for example). If this is an isolated piece of code then there should be no problems, however if this literal value is embedded amongst a lot of other literal values, then knowing how to change this value '10' everywhere can create a significant problem.

For example, in the following code, are these '10's equivalent, or do they refer to the size of different objects.
```for(int i=0; i<10; i++) { /* ... do something ... */ }
/*....*/
for(int j=0; j<10; j++) { /* ... do something else ... */ }```
Without reading carefully the underlying source it is impossible to tell.

## Better Approach

The preferred method is to place a `#define` or constant definition, at the front of your program, e.g.
```#define ARRAY_LEN 10
for(int i=0; i<ARRAY_LEN; i++) { /* ... do something ... */ }
/*....*/
for(int j=0; j<ARRAY_LEN; j++) { /* ... do something else ... */ }```
Now there is no possibility of confusion and both loops clearly loop over the same sized containers.

Alternatively you can use `enums`
```enum { array_A_size=10; array_B_size=10; };
for(int i=0; i<array_A_size; i++) { /* ... do something ... */ }
/*....*/
for(int j=0; j<array_B_size; j++) { /* ... do something else ... */ }```
In this instance it is obvious that the two loops work on different (potentially) sized arrays.

## Performance

The great think about `enum` or `#define` is that there is no performance overhead to their use. The compiler will substitute the appropriate values into your code and compile the program as if you had written it with all the Magic numbers in there (as in our first example).