tags:

views:

185

answers:

5

Obviously the point of using named constants over magic numbers is for code clarity and for not having to go through code changing numbers throughout.

However, what do you do if you just have a number used just once in a function? Say you have a short member function that uses an object's velocity (which we'll say won't change) to calculate its motion, but this is the only function that uses that velocity. Would you...

A) Give the class a named static constant to use

B) Put a named constant in the function

C) Use the magic number but comment it

D) Other...

I am kind of leaning towards using a magic number and commenting it if the number is ONLY BEING USED ONCE, but I'd like to hear others' thoughts.

Edit: Does putting a named constant in a function called many times and assigning to it have performance implications? If it does I guess the best approach would be to put the constant in a namespace or make it a class variable, etc.

+5  A: 

Just move it up:

void do_something(void)
{
    const float InitialVelocity = 5.0f;

    something = InitialVelocity;
    // etc.
}
GMan
Does this have any performance implications if you are in a high performance environment?
Anonymous
No, unless your compiler is utterly brain-dead. MSVC and GCC (with -O3) will just treat that number as a compile-time constant.
Crashworks
Thanks Crash. Very helpful.
Anonymous
You can always check to see what the compiler really emits for a given .cpp file by telling it to emit an assembly listing along with the object code. That's the `/FAcs` option in MSVC and `-S` in GCC.
Crashworks
+3  A: 

Say you have a short member function that uses an object's velocity

You said it, the constant has a name:

const type object_velocity = ....;

Magic numbers are my enemies :)

AraK
+1  A: 

I'd use a function-local named constant, at a minimum. Usually I'd use an anonymous namespace named constant to make the value available throughout the source file, assuming that it might be useful later to other functions.

Drew Hall
A: 

Use Eclipses refactoring functions to move the constant into a named variable of the method.

Kelly French
A: 

Use it as a constant inside the function:

const int x = myMagicNumber; //Now document the magic.
Sai Charan