50

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;
Jack0x539
  • 616
  • 6
  • 12
  • 35
    To me, this sounds like people taking the "avoid hardcoding numbers" guideline a bit too far. In almost all circumstances, it's better to use predefined constants so that you can easily change each occurrence of a number later on. But naming them after their content seems like a terrible idea. – Lee White Feb 26 '14 at 10:15
  • 11
    I think if you examine the code of resize.c, you will find that those numbers are not constants, but will in fact be set to all the different powers of five and seven lower than the end value, as the backups are iterated through. – Ivy Gorven Feb 26 '14 at 10:23
  • Just saw that Buddy, and commented further down here, but thanks, I was looking naively at that code, and after a harder look I saw that they were passed by reference to another call. – Jack0x539 Feb 26 '14 at 10:29
  • 1
    Whenever `five` changes it's meaning to say `7` or something else, you'd only have to change it in one place. ;) Sarcasm aside: This is taking "avoid hardcoded/magic numbers" a step or two too far. – waka Feb 26 '14 at 10:39
  • 6
    So in fact `five` and `seven` have *bad* naming and the name would reflect that it is to represent a powerOf .. . (Note though that there are not marked `const`)... – Jarod42 Feb 26 '14 at 10:49
  • 5
    Maybe they're following the guide to write unmaintainable code? https://www.thc.org/root/phun/unmaintain.html (under "Miscellaneous Techniques", bullet #18) – jamesdlin Feb 26 '14 at 11:02
  • 1
    You mean just in case that five one day is redefined to mean 6? – PlasmaHH Feb 26 '14 at 11:18
  • This is not what you are asking, but a common "named number" is `PI`. Because it's impractical (and perhaps impossible) to include the exact value of π in code, an approximation is used. Now it becomes reasonable to make it a constant - to explicitly define the approximation you chose, in one place, where it can easily be changed if another approximation is later desired. Although the pedant would say that most libraries should call it `APPROXIMATE_VALUE_OF_PI` instead of `PI` - it's not actually π, after all. – Superbest Feb 26 '14 at 11:19
  • @LeeWhite and everyone arguing the "simple guideline taken too far" explanation: I am a bit skeptical of this. Is *every* instance of named number constants like these an error? Is there no legitimate reason for it (at least with integers)? – Superbest Feb 26 '14 at 11:23
  • @Superbest: The example given by the OP is not an error. However, it seems like overkill to assig `5` to a variable named `five`. But if you have a `for`-loop and it needs to be looping a specified amount of times, it would be good practice (and easier to maintain) to set this specific amount in a good named constant. Then, whenever the specification changes, you can simply change the value of the constant. – waka Feb 26 '14 at 11:31
  • 2
    No one would be surprised to see *constants* handled in this way -- it seems the spirit of the OP question is, why would this be done with a *variable*? One speculation: maybe the developer moves between languages and is more familiar with a language that doesn't have true constants (like Python or PHP), and is declaring a variable that in practice is used like a constant. – Chris Johnson Feb 26 '14 at 13:20
  • 2
    @ChrisJohnson I personally would be very surprised to see constants handled in this way. Ok I wouldn't be suprised, but it would lead me to question the organisation that wrote it (often the developers are just following a foolish coding standard) – Richard Tingle Feb 26 '14 at 14:50
  • 1
    These numbers do not represent the numbers 5 and 7 in the linux kernel. Read the docs! (Hint, the previous line has `three = 1` ) – Benjamin Gruenbaum Feb 27 '14 at 22:40
  • 1
    Many are criticizing the code without reading it. Go read the code. If you can't understand it, then explain how the variable names impeded your comprehension. – D Krueger Feb 27 '14 at 23:36
  • Not saying it's the best way, but it could be that someone wanted to be able to change the value later via refactoring tools. It would be easier and more reliable than searching for 5. – GaTechThomas Mar 03 '14 at 14:46

10 Answers10

84

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.

Zebra North
  • 11,412
  • 7
  • 37
  • 49
  • 2
    The reason I started wondering about this was because in resize.c (linux source), `unsigned three = 1;` which seems strange, then again I don't know what they're being used for in this example, and although I say they are only used once, they are actually passed by reference by another function call, so anything could be happening, kinda makes sense here now I've looked harder at the code. – Jack0x539 Feb 26 '14 at 10:28
  • 1
    It may be EVEN WORSE than this actually. Maybe if they use the magic number 5 in one spot, and they want to change it later, then changing five to be not 5 is dumb yes. But what if while the value was 5, you needed to use the magic number 5 somewhere else? So you just decided to use the same constant. Now when you change five to 7 you actually break everything. – Cruncher Feb 26 '14 at 14:33
  • Yep that's what I was implying, along with the fact that it is incredibly misleading, it will break any other instances. It's an all-round disaster. – Zebra North Feb 26 '14 at 14:37
  • 2
    There is nothing wrong in naming a constant which will never change. like `One` `Zero` etc. Don't take me wrong I mean constants only. 1 is always going to be one, no matter what. but if an entity that may change later don't name it number. example `Decimal.One` is a constant defined in `decimal` class, because that's never gonna change. – Sriram Sakthivel Feb 26 '14 at 14:42
  • 4
    @SriramSakthivel It does bring the question though: what is the benifit of defining a constant `1` as `ONE`? – Richard Tingle Feb 26 '14 at 15:13
  • @RichardTingle I should admit that am speechless, benefit I cant think of other than readability. That brings up a argument. Why would you ever need a `const` keyword? You could anywhere use the constant values isn't it? – Sriram Sakthivel Feb 26 '14 at 15:17
  • 1
    @SriramSakthivel Indeed, I can think of no reason anyone would ever write `constant int five = 7` (or other language variant). I has always seemed insane to me – Richard Tingle Feb 26 '14 at 15:19
  • 21
    `const` is useful for when you have *meaningful* names. `const MaximumPrice = 7` is useful. `const seven = 7` is not useful. – Zebra North Feb 26 '14 at 15:22
  • 5
    @SriramSakthivel I strongly disagree that it's more readable! What would you rather see: `if (x == OneThousandTwoHundredAndThirtyFour)` or `if (x == 1234)`? – Zebra North Feb 26 '14 at 15:25
  • Agreed :|. You're right. but... I guess there should be some reason to define constants like `Decimal.One` in .Net FW. I don't think designers of BCL are dumb enough to expose such constant in public API without any reason :) – Sriram Sakthivel Feb 26 '14 at 15:30
  • 2
    @SriramSakthivel see this [answer](http://stackoverflow.com/a/745638/151019) for Decimal.One - there is more than just a constant – mmmmmm Feb 26 '14 at 16:18
  • In any computations it is entirely necessary to prevent small mistakes (mistaking 0 for O, and 1 for l, and swapping 0 and 1) from drastically altering the meaning of the code. It also helps readability a bit. – Deer Hunter Feb 27 '14 at 05:31
  • 4
    Anyone who uses O and I for variable names deserves what they get... :P – Zebra North Feb 27 '14 at 09:51
  • 1
    @DeerHunter Fair point, but every reasonable programming font has `oO0` and `lI1` and `'\`"` and others purposefully made very distinct – Kos Feb 27 '14 at 10:24
  • @MrZebra: Agreed; I would go further and say anyone who uses *any* single letter for a variable name deserves what they get - two letter minimum is my rule of thumb, and that short only for extremely tight scope (like a `for` loop). – Lawrence Dol Feb 27 '14 at 17:21
  • @Kos: Nope: Droid Sans Mono `O` and `0` are nearly identical. Consolas `1` and `l` are nearly identical. Especially at small sizes. And both of these are "programming" fonts. – Lawrence Dol Feb 27 '14 at 17:24
  • 1
    This would make sense if `five` is more expensive than a primitive to construct. For example, the Java `BigDecimal` class has constants such as `ZERO`, `ONE`, and `TEN`. But those make sense, since they are common numbers and the constructor for the class can potentially be expensive to call (e.g. by passing in a string). –  Feb 27 '14 at 22:30
  • @SoftwareMonkey Poor font engineering does happen, lack of slashed 0 being the most obvious omission (Droid Sans). Ubuntu Mono and Deja Vu Sans Mono do a particularly great job of being unambiguous (like the rounded lowercase L). – Kos Feb 28 '14 at 09:45
47

Well named variables

Giving proper names to variables can dramatically clarify code, such as

constant int MAXIMUM_PRESSURE_VALUE=2;

This gives two key advantages:

  • The value MAXIMUM_PRESSURE_VALUE may be used in many different places, if for whatever reason that value changes you need to change it in only one place.

  • Where used it immediately shows what the function is doing, for example the following code obviously checks if the pressure is dangerously high:

    if (pressure>MAXIMUM_PRESSURE_VALUE){
        //without me telling you you can guess there'll be some safety protection in here
    }
    

Poorly named variables

However, everything has a counter argument and what you have shown looks very like a good idea taken so far that it makes no sense. Defining TWO as 2 doesn't add any value

constant int TWO=2;
  • The value TWO may be used in many different places, perhaps to double things, perhaps to access an index. If in the future you need to change the index you cannot just change to int TWO=3; because that would affect all the other (completely unrelated) ways you've used TWO, now you'd be tripling instead of doubling etc
  • Where used it gives you no more information than if you just used "2". Compare the following two pieces of code:

    if (pressure>2){
        //2 might be good, I have no idea what happens here
    }
    

    or

    if (pressure>TWO){
        //TWO means 2, 2 might be good, I still have no idea what happens here
    }
    
  • Worse still (as seems to be the case here) TWO may not equal 2, if so this is a form of obfuscation where the intention is to make the code less clear: obviously it achieves that.

The usual reason for this is a coding standard which forbids magic numbers but doesn't count TWO as a magic number; which of course it is! 99% of the time you want to use a meaningful variable name but in that 1% of the time using TWO instead of 2 gains you nothing (Sorry, I mean ZERO).

this code is inspired by Java but is intended to be language agnostic

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
  • 1
    The counter-example here is a non-primitive such as Java's `BigDecimal` class whose constructor is potentially expensive to call. Calling it once for a common value and caching the result can be beneficial. –  Feb 27 '14 at 22:31
  • @John O yes, if its not a primitive then all bets are off – Richard Tingle Feb 27 '14 at 22:40
35

Short version:

  • A constant five that just holds the number five is pretty useless. Don't go around making these for no reason (sometimes you have to because of syntax or typing rules, though).
  • The named variables in Quaternion.cs aren't strictly necessary, but you can make the case for the code being significantly more readable with them than without.
  • The named variables in ext4/resize.c aren't constants at all. They're tersely-named counters. Their names obscure their function a bit, but this code actually does correctly follow the project's specialized coding standards.

What's going on with Quaternion.cs?

This one's pretty easy.

Right after this:

double zero = 0;
double one = 1;

The code does this:

return zero.GetHashCode() ^ one.GetHashCode();

Without the local variables, what does the alternative look like?

return 0.0.GetHashCode() ^ 1.0.GetHashCode(); // doubles, not ints!

What a mess! Readability is definitely on the side of creating the locals here. Moreover, I think explicitly naming the variables indicates "We've thought about this carefully" much more clearly than just writing a single confusing return statement would.

What's going on with resize.c?

In the case of ext4/resize.c, these numbers aren't actually constants at all. If you follow the code, you'll see that they're counters and their values actually change over multiple iterations of a while loop.

Note how they're initialized:

unsigned three = 1;
unsigned five = 5;
unsigned seven = 7;

Three equals one, huh? What's that about?

See, what actually happens is that update_backups passes these variables by reference to the function ext4_list_backups:

/*
 * Iterate through the groups which hold BACKUP superblock/GDT copies in an
 * ext4 filesystem.  The counters should be initialized to 1, 5, and 7 before
 * calling this for the first time.  In a sparse filesystem it will be the
 * sequence of powers of 3, 5, and 7: 1, 3, 5, 7, 9, 25, 27, 49, 81, ...
 * For a non-sparse filesystem it will be every group: 1, 2, 3, 4, ...
 */
static unsigned ext4_list_backups(struct super_block *sb, unsigned *three,
                                  unsigned *five, unsigned *seven)

They're counters that are preserved over the course of multiple calls. If you look at the function body, you'll see that it's juggling the counters to find the next power of 3, 5, or 7, creating the sequence you see in the comment: 1, 3, 5, 7, 9, 25, 27, &c.

Now, for the weirdest part: the variable three is initialized to 1 because 30 = 1. The power 0 is a special case, though, because it's the only time 3x = 5x = 7x. Try your hand at rewriting ext4_list_backups to work with all three counters initialized to 1 (30, 50, 70) and you'll see how much more cumbersome the code becomes. Sometimes it's easier to just tell the caller to do something funky (initialize the list to 1, 5, 7) in the comments.

So, is five = 5 good coding style?

Is "five" a good name for the thing that the variable five represents in resize.c? In my opinion, it's not a style you should emulate in just any random project you take on. The simple name five doesn't communicate much about the purpose of the variable. If you're working on a web application or rapidly prototyping a video chat client or something and decide to name a variable five, you're probably going to create headaches and annoyance for anyone else who needs to maintain and modify your code.

However, this is one example where generalities about programming don't paint the full picture. Take a look at the kernel's coding style document, particularly the chapter on naming.

GLOBAL variables (to be used only if you really need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that "count_active_users()" or similar, you should not call it "cntusr()".

...

LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called "i". Calling it "loop_counter" is non-productive, if there is no chance of it being mis-understood. Similarly, "tmp" can be just about any type of variable that is used to hold a temporary value.

If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome. See chapter 6 (Functions).

Part of this is C-style coding tradition. Part of it is purposeful social engineering. A lot of kernel code is sensitive stuff, and it's been revised and tested many times. Since Linux is a big open-source project, it's not really hurting for contributions — in most ways, the bigger challenge is checking those contributions for quality.

Calling that variable five instead of something like nextPowerOfFive is a way to discourage contributors from meddling in code they don't understand. It's an attempt to force you to really read the code you're modifying in detail, line by line, before you try to make any changes.

Did the kernel maintainers make the right decision? I can't say. But it's clearly a purposeful move.

Alex P
  • 1,559
  • 11
  • 23
  • good answer, I was wondering about the context of the constants in that code – Serve Laurijssen Feb 27 '14 at 15:13
  • 7
    I'd call this an *excellent* answer. The ones that currently have more votes are certainly not wrong. They give good advice and fine reasoning. But they just regurgitate intuitive stuff that confirms the OP's suspicions. They're one level of regurgitation above "don't use magic numbers". This answer (proper credit also goes to some of the comments on the main question which head in this direction) delves deeper and really addresses the examples provided by the OP. – John Y Feb 27 '14 at 21:36
  • 1
    This answer is great. Only by reading the code can one determine if a variable is well named. The usage of `three`, `five`, and `seven` didn't inhibit Alex's understanding of the code, so what's the problem? We should code in a way that is clear to ourselves and others. If that violates coding guidelines, then the guidelines are erroneous, not the code. – D Krueger Feb 27 '14 at 22:07
11

My organisation have certain programming guidelines, one of which is the use of magic numbers...

eg:

if (input == 3) //3 what? Elephants?....3 really is the magic number here...

This would be changed to:

#define INPUT_1_VOLTAGE_THRESHOLD 3u 
if (input == INPUT_1_VOLTAGE_THRESHOLD) //Not elephants :(

We also have a source file with -200,000 -> 200,000 #defined in the format:

#define MINUS_TWO_ZERO_ZERO_ZERO_ZERO_ZERO -200000

which can be used in place of magic numbers, for example when referencing a specific index of an array.

I imagine this has been done for "Readability".

Sarima
  • 749
  • 7
  • 21
  • 12
    First example is great for showing why you would 'name' a number. The 2nd though? I can't see how that helps anyone anywhere! – cjb110 Feb 26 '14 at 10:07
  • @cjb110 It may not help, however it saves time having to define every number when you need it. We simply include the file, and hey presto, 400,000 #defines done. Tbh, it was just to save time in the long run. – Sarima Feb 26 '14 at 10:14
  • TWELVE_VOLTS makes perfect sense to me, and i do the same thing myself, but your example is not `if (input == twelve)` which if the bit I was struggling to understand :p – Jack0x539 Feb 26 '14 at 10:24
  • 9
    Uh, what? `TWELVE_VOLTS` is defined on a project-by-project basis? So `TWELVE_VOLTS` might actually represent, say, 13V? If so, that's horrible. What would make your code more readable (and less error-prone) is if it was clear what units your *variables* represented; e.g. `if (inputVolts == 12)`. – jamesdlin Feb 26 '14 at 10:50
  • 1
    Not quite, project A might need "input" to be TWELVE_VOLTS, but project B would need it to be THIRTEEN_VOLTS. However, i do like your suggestion of "inputVolts" over "input". – Sarima Feb 26 '14 at 10:58
  • 5
    This example is confusing. The two big reasons for not having magic numbers are readability and ability to easily and safely alter code. "Twelve volts" is about as descriptive as "12", so the first concern has not been satisfied. It would be bizarre to expect "twelve volts" to mean anything other than twelve volts, so the second concern is also not addressed. A "constant" like this is as good as a magic number (in fact worse, because it adds complexity). It should be called `inputVoltage` - which brings us back to the original question. – Superbest Feb 26 '14 at 11:15
  • 3
    Having `TWELVE_VOLTS` in one project and `THIRTEEN_VOLTS` in another is silly; those constants have no semantic meaning. In a sane system, you'd have a constant named something like `INPUT_VOLTAGE` and set it differently for different projects. There's some sarcasm in your answer, but I'm afraid that some people will misinterpret it and think that you're advocating this sort of horrible practice. – jamesdlin Feb 26 '14 at 11:23
  • 1
    I should probably explain this a little better, coming from an embedded control system background, i would normally define 12 as "INPUT_1_THRESHOLD". – Sarima Feb 26 '14 at 11:46
  • 2
    This is horrible. The correct way is to either name your variable a quantity which implies voltage as units, or/and define a Voltage integer type (this last one might not be reasonable for low-level languages like C, but for instance in C# you could that fairly easily and have the `ToString()` method append a `V` at the end of the voltage representation and you don't get much more self-documenting than that). I won't even comment on the `MINUS_TWO_ZERO_ZERO_ZERO_ZERO_ZERO` macro, I died a little inside reading it. – Thomas Feb 26 '14 at 11:48
  • @Thomas whats wrong with the MINUS_TWO_ZERO_ZERO_ZERO_ZERO_ZERO? – Sarima Feb 26 '14 at 12:06
  • 5
    @Joshpbarron What’s wrong with it is that it serves literally no purpose at all. The symbol "2" is replaced with the symbol "TWO", they both have exactly the same meaning so are 100% equivalent. On the other hand your first example is an example of exactly what *should* be done to avoided magic numbers; give a meaningful name to a value – Richard Tingle Feb 26 '14 at 13:07
  • Understood, however what about accessing an index of an array? Should i have Names[1], Names[ONE] or Names[INDEX_1]? – Sarima Feb 26 '14 at 13:19
  • @Joshpbarron It makes no difference. Usually you would want a meaningful name, but assuming there isn't one (which happens occasionally) you might as well use `Names[1]`. I've expanded on this a little in my [answer](http://stackoverflow.com/a/22042928/2187042) – Richard Tingle Feb 26 '14 at 13:31
  • 5
    `ONE` is just as much of a magic number as `1` – Richard Tingle Feb 26 '14 at 13:33
  • 3
    @RichardTingle It might even be more magic, when it doesn't do what you expect it to. – Cruncher Feb 26 '14 at 14:39
  • 4
    "We also have a source file with -200,000 -> 200,000 #defined.." That's wrong on multiple levels. I would fire whoever thought of that, and whoever used it. – Kevin Feb 27 '14 at 03:18
7

The numbers 0, 1, ... are integers. Here, the 'named variables' give the integer a different type. It might be more reasonable to specify these constant (const unsigned five = 5;)

  • 3
    I see, so instead of writing `return 1f;` or `return 1L;` you would `float one = 1; return one;` or `long one = 1; return one;` – Jack0x539 Feb 26 '14 at 10:08
7

I've used something akin to that a couple times to write values to files:

const int32_t zero = 0 ;

fwrite( &zero, sizeof(zero), 1, myfile );

fwrite accepts a const pointer, but if some function needs a non const pointer, you'll end up using a non const variable.

P.S.: That always keeps me wondering what may be the sizeof zero .

Diego Sánchez
  • 539
  • 2
  • 12
  • Okay, I have to admit, this is actually legitimate usage. However, any variables you name in this way should have a narrow scope, and the actual cases where you'd want to use a name like `zero` instead of a more meaningful name are rather limited. – jamesdlin Feb 26 '14 at 20:39
  • +1 - this is exactly what the [resize.c](http://lxr.free-electrons.com/source/fs/ext3/resize.c) mentioned in the question is doing - see line 398. Predictably, the code's already run amock - line 391 has `unsigned three = 1;`. – Tony Delroy Feb 27 '14 at 04:38
  • @TonyD 3^0 = 1. I guess it would've been more consistent to start all three counters at 1, but three = 1, five = 5, seven = 7 is a trivial optimization that makes sense in the context of the count-by-powers trick that it's doing. – Alex P Feb 27 '14 at 07:55
6

How do you come to a conslusion that it is used only once? It is public, it could be used any number of times from any assembly.

public static readonly Quaternion Zero = new Quaternion();
public static readonly Quaternion One = new Quaternion(1.0f, 1.0f, 1.0f, 1.0f);

Same thing applies to .Net framework decimal class. which also exposes public constants like this.

public const decimal One = 1m;
public const decimal Zero = 0m;
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 2
    I come to that conclusion because I was looking at the code. `private static int GetIdentityHashCode() { // This code is called only once. double zero = 0; double one = 1; // return zero.GetHashCode() ^ zero.GetHashCode() ^ zero.GetHashCode() ^ one.GetHashCode(); // But this expression can be simplified because the first two hash codes cancel. return zero.GetHashCode() ^ one.GetHashCode(); }` – Jack0x539 Feb 26 '14 at 10:21
  • @Jack0x539 in your example you can't say `1.GetHashCode()` – concept3d Feb 26 '14 at 10:23
  • @Jack0x539 if it is a local variable there is no good reason to do that other than readability. I often do that but here it is a local variable I'll probably declare it as `const` – Sriram Sakthivel Feb 26 '14 at 10:25
  • 2
    @concept3d You can do that, try it out :) – Sriram Sakthivel Feb 26 '14 at 10:25
6

Numbers are often given a name when these numbers have special meaning.

For example in the Quaternion case the identity quaternion and unit length quaternion have special meaning and are frequently used in a special context. Namely Quaternion with (0,0,0,1) is an identity quaternion so it's a common practice to define them instead of using magic numbers.

For example

// define as static 
static Quaternion Identity = new Quaternion(0,0,0,1);


Quaternion Q1 = Quaternion.Identity;
//or 
if ( Q1.Length == Unit ) // not considering floating point error
Floris
  • 45,857
  • 6
  • 70
  • 122
concept3d
  • 2,248
  • 12
  • 21
  • I didn't downvote, but do think it unfair to assume it's a "hater". This question is specifically about cases where the constant doesn't add abstraction and isn't obviously useful; this answer does nothing to address that scenario. I don't understand all the answers explaining the generally accepted best practice (or why they've attracted upvotes) - it's the seeming exception that's of interest. – Tony Delroy Feb 27 '14 at 04:35
2

One of my first programming jobs was on a PDP 11 using Basic. The Basic interpreter allocated memory to every number required, so every time the program mentioned 0, a byte or two would be used to store the number 0. Of course back in those days memory was a lot more limited than today and so it was important to conserve.

Every program in that work place started with:

10  U0%=0
20  U1%=1

That is, for those who have forgotten their Basic:

Line number 10: create an integer variable called U0 and assign it the number 0
Line number 20: create an integer variable called U1 and assign it the number 1

These variables, by local convention, never held any other value, so they were effectively constants. They allowed 0 and 1 to be used throughout the program without wasting any memory.

Aaaaah, the good old days!

MattClarke
  • 1,647
  • 1
  • 11
  • 32
1

some times it's more readable to write:

double pi=3.14; //Constant or even not constant
...
CircleArea=pi*r*r;

instead of:

CircleArea=3.14*r*r;

and may be you would use pi more again (you are not sure but you think it's possible later or in other classes if they are public)

and then if you want to change pi=3.14 into pi=3.141596 it's easier.

and some other like e=2.71, Avogadro and etc.

Behnam Safari
  • 2,941
  • 6
  • 27
  • 42
  • 3
    Far more readable for mathematical constants such as PI yes, and you don't want to be typing out 10 digits every time, I know that, but it was the usage in the examples that I gave that I did not understand the value of. – Jack0x539 Feb 26 '14 at 10:25
  • @Jack0x539 As I noted in my comment to your question, the reason is not "don't want to type out 10 digits". It's impossible to actually type out pi, so you must settle on some approximate form - and it cannot be conclusively decided how many digits is the right amount of precision, so you must allow for changing precision later. Technically the constant called `pi` is not actually pi but an approximation - hence, unlike pi, this so-called `pi` is not necessarily constant between compilations. – Superbest Feb 26 '14 at 11:26