Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named numbers as variables [closed]

I've seen this a couple of times recently in high profile code, where constant values are defined as variables, named after the value, then used only once. I wondered why it gets done?

E.g. Linux Source (resize.c)

unsigned five = 5; unsigned seven = 7; 

E.g. C#.NET Source (Quaternion.cs)

double zero = 0; double one = 1; 
like image 408
Jack0x539 Avatar asked Feb 26 '14 09:02

Jack0x539


People also ask

Is it OK to use numbers in variable names?

After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed.

Why should variable names not start with numbers?

We can not specify the identifier which starts with a number because there are seven phases of compiler as follows. None of above supports that a variable starts with a number. This is because the compiler gets confused if is a number or identifier until it reaches an alphabet after the numbers.

What is not allowed in naming a variable?

Specifically, spaces are not permitted in the variable names, as variable name must be a single word. Variable name may not start with a digit or underscore, and may not end with an underscore. Double underscores are not permitted in variable name.


1 Answers

Naming numbers is terrible practice, one day something will need to change, and you'll end up with unsigned five = 7.

If it has some meaning, give it a meaningful name. The 'magic number' five is no improvement over the magic number 5, it's worse because it might not actually equal 5.

This kind of thing generally arises from some cargo-cult style programming style guidelines where someone heard that "magic numbers are bad" and forbade their use without fully understanding why.

like image 120
MrZebra Avatar answered Oct 14 '22 21:10

MrZebra