简体   繁体   中英

A case where named constants are not needed over magic numbers

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.

Just move it up:

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

    something = InitialVelocity;
    // etc.
}

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 :)

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.

使用Eclipse重构函数将常量移动到方法的命名变量中。

在函数内部将其用作常量:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM