0

I want to avoid numbers used directly in expressions without obvious meaning. However, if a number is used only once, as an argument passed into a function, and that number can be easily changed without breaking the program, is that number considered a magic number?

For example, I have a function double doSimulation(double alpha, double beta, unsigned count) where the parameters are to the simulation model. In my application code, I type in double x = doSimulation(0.5, 0.2, 100) as part of the application logic, where the numbers 0.5, 0.2 and 100 are prone to change and not used anywhere else, i.e. they can be changed directly to improve the model.

In this case, are the numbers considered magic numbers? Is it redundant to declare

const double ALPHA = 0.5;
const double BETA = 0.5;
const unsigned COUNT = 100;

and use them only once, as the numbers are already named by means of function parameter?

Michael Tsang
  • 810
  • 2
  • 7
  • 13
  • No. A magic number is one which has meaning outside of your code. Ie specialObject = DataBase.GetObject(13) // the special object I want is always id 13 – Ewan Jul 02 '15 at 07:43
  • Magic numbers are by definition parameters deemed constant throughout your program. If you can replace 0.5, 0.2, and 100 with constants, than it should make just as much sense to use the magic numbers directly in your function and not as parameters. If that doesn't make sense in your case, then they *aren't* magic numbers but should remain function parameters. – Neil Jul 02 '15 at 07:44

1 Answers1

3

Yes, they still are. The point behind the 'magic number' concept is that they are meaningless by themselves. What does 0.5 mean? Once you give it a variable name, you've turned that value into a thing with meaning. It also helps to edit or update them, if you know all your magic numbers are held in a certain place (eg at the top of your class/header/etc) then you can change the value confident that its being changed in the right place.

That you can also be confident its changed consistently across you program if (or when) it gets used multiple times is a bonus.

The only time not to use a variable to define these is if the value never changes, is a constant and is not going to ever change. There's no need to write 100 as a constant when its used for calculating percentages.

gbjbaanb
  • 48,354
  • 6
  • 102
  • 172
  • 0.5 has already a name. The name is given in the signature of the function called because I directly pass it to a function. – Michael Tsang Jul 03 '15 at 09:12