5

I can't see the point of constants. For example I can use the famous example of PI:

PI = float(3.14) 

Here I get the job done without a constant. Who cares if the value never changes during the lifetime of the program or if it's best practise.

I can define PI as a variable and get the same task done just as well.

15
  • 5
    To me PI = float(3.14) looks like something I'd call a "constant". What exactly do you mean by that term? – Ixrec Mar 21 '16 at 22:54
  • 23
    "Who cares if it's programming best practise"? I do, because I will have to maintain your unclear code after you move on to the next job. – Kilian Foth Mar 21 '16 at 23:11
  • 3
    That's a pretty lousy example as that will be insufficient precision for just about every application that needs to use Pi in the first place. – whatsisname Mar 21 '16 at 23:47
  • 9
    4 downvotes expressing disagreement with the OP instead of focusing on question quality, 5 mods putting pressure to edit or close the question and yet, 2 answers with score of 5+. In the meantime, people on meta are still trying to figure what is wrong with P.SE ... Sorry, but this is lame. – user44761 Mar 22 '16 at 11:35
  • 12
    We should probably stop being allergic to questions like this. It's the perfect example of a software design question, even if it's a bit basic and slightly opinionated. It's the kind of question we want here; sure beats "fix my broken code" or "convince my boss." – Robert Harvey Mar 22 '16 at 15:26
9

Conceptually, the options to assign a value to a variable or a constant differ only in one way : A compiler would give a warning when you attempt to reassign a constant

You are correct. If you assign the value to a variable instead of a constant, it would get the job done as long as you are taking care to not change the value assigned to it.

It may seem redundant to you, for example if you're making a program to find area of a circle of a given radius, you may write

float pi =  3.14
float area (float r) : 
    return pi*r*r

and think to yourself that if someone were to change the value of pi to something else like 2.5, then they are really the victims of their own stupidity.

And no one wants to burden themselves with an unneeded feature.

However, programmers tend to eliminate as many possible future problems as they can. It may happen that if the program is large and has many programmers working on it, someone may redefine your variable (to make it work for them) but then the next call to your function that depended on the correct value of your variable would then return erroneous results.

Now there are two ways to eliminate this possibility, either you could make your variable local to the function itself, but that results in redundancy because you would have to do so for each function that refers to it.

Or you could use the nifty feature that's provided by the programming language and declare your value a constant so that the compiler would give a warning if the value of constant is tried to be reassigned.

1
  • 1
    Definitely not the raison d'etre, but another benefit of assigning to a constant is that it gives the compiler more information. This additional information can potentially be leveraged to provide performance benefits. For example, the consts in C# are inlined into the calling code, even across assemblies (which means changing a const requires a recompile of all callers). – Brian Mar 23 '16 at 14:56
20
  1. The English name makes it clear what the purpose of the number is.
  2. The precision of Pi is the same throughout your program.
  3. Pi is defined in one place, so you don't have to change it everywhere if you decide to change the number of decimal places.
  4. Letting the compiler enforce a constant means that there is no possibility of any part of the code ever changing it to something else, eliminating a source of potentially obscure bugs.
6
  • 1
    The OP stated that none of this matters. – JeffO Mar 22 '16 at 15:47
  • @JeffO: The OP asked why. – Robert Harvey Mar 22 '16 at 16:43
  • 2
    The OP proposed to define PI as a variable, not to use float(3.14) instead. Only 4. is relevant to the question. – Florian F Mar 22 '16 at 17:29
  • 5
    Then read #4. If I had only said #4, people would have complained that I wasn't thorough enough. – Robert Harvey Mar 22 '16 at 17:32
  • @FlorianF I'm not convinced the OP did exclude any of these four points in the question, which is the whole reason I left a comment asking what the OP meant by "constant" instead of answering myself. – Ixrec Mar 22 '16 at 21:59
13

who cares if the value never changes during the lifetime of the program or it's programing best practise.

Who cares? People who need to maintain your code.

What happens if your project manager comes back to you in several months and says that "3.14" is no longer a good enough approximation for pi for your application? He wants to make the program more accurate because it will be used to build the next space shuttle and it needs accuracy up to 8 decimal points.

What do you do? Just do a massive find and replace of "3.14" to "3.14159265" across all your code in your project? Well, congratulations. Now you've messed up another calculation somewhere else where another brilliant programmer hard-coded the value "23.14994". Now that value is "23.14159265994" and the space shuttle just blew up.

Constants help keep values consistent where you need them. Sure, you don't expect your game of Tic-Tac-Toe to have more than three columns and three rows, but someone may want to expand the game to a 5-5 grid. It also makes your code more readable. You can also usually refactor your code in the future by right-clicking a variable/constant and renaming it across the application or file.

EDIT: The original title of the question was "Why do we need constants in programming?" Since the question was changed to "Why can't we just use variables instead of constants?" I'll answer that question, too.

Variables can change. Constants can't. If someone decides they only need two digits of precision and your variable holds 8 digits of precision, they may truncate the insignificant digits from your variable. Unfortunately, this can cause problems for other parts of the app that were relying on the original, more precise value. By making the value a constant, this would result in a compile time error and would maintain the integrity of the application.

2
  • 4
    Downvoted because that's not what the asker asked. He did not ask why we declare names to such values - he asked why we need to take special measures to make sure these values don't change during runtime. – Idan Arye Mar 22 '16 at 14:39
  • 1
    @IdanArye Actually OP asked "who cares?". And then asserted "get the same task done just as well". Who cares are those people that understand that assertion is false. – paparazzo Mar 22 '16 at 19:59
6

Communication of Intent

In your example, you have defined a mutable variable PI, which you can reference throughout your program. You've created DRY code, which only needs to be updated in a single place if you ever want to change its definition. This is good, and it works for small programs where there's only one developer, and not a lot of code.

As a code base grows larger, however, and as more people start working in the code, it becomes much more important to communicate your intent. Although most people are probably aware that Pi is a mathematical constant, and aren't expecting it to change, the same isn't true for most constants. By declaring something as a constant, you are telling other developers (including your future self) about what that constant means.

What does a Constant communicate?

When you see that a value is declared as a constant, the code is communicating the following things to you, as a developer:

  1. This value will never change during the runtime of the program.
  2. This value is probably thread safe (it will only ever be read, not written to).
  3. This value is likely referenced in many areas throughout the code.
  4. The name of the value likely tells you something important about what it means.
    • Most of us know that 3.14 is an approximation of Pi, but many constants are meaningless without a name. if (i > MaxNumberOfUsers) is a lot more meaningful than if (i > 10).

What other benefits can Constants confer?

Declaring a value as constant is often also telling the compiler some things (though this varies depending on your language and compiler):

Many compilers will optimize constant values at compile time, and insert their results directly into the code.

// No calculation will take place at runtime - all of these values
// can be replaced with their calculated results at compile time
const long BytesPerKilobyte = 1024;
const long BytesPerMegabyte = 1024 * BytesPerKilobyte; // Compiles as 1048576
const long BytesPerGigabyte = 1024 * BytesPerMegabyte; // Compiles as 1073741824

// ... elsewhere in the code ...
const long maxFileSize = BytesPerMegabyte * 40;
if (fileSize > maxFileSize) // actually compiles to `if (fileSize > 41943040) {...}`
{
    println("The file is too large to work with");
}

So...

When I started learning programming I didn't understand the point of constants. I had never worked in a project with more than a few classes, and it was easy to keep everything straight in my head.

Most code isn't like this. Most code exists in very large environments, being maintained by multiple people, at different times. As the projects you work on grow larger, it becomes more and more important to be able to communicate to other developers and to yourself what your code is intended to do.

In these sorts of environments, you will appreciate anything take away some of the mental load that comes with keeping everything straight in your head.

3

As projects get bigger and bigger, they get harder and harder to maintain - mainly because the human mind is limited in the number of things it can keep in it's immediate context. To overcome this, we usually want to break the project into smaller, simpler components, so we can work on one component without having to keep in mind how the other components work. Even if we use other components, we would like to use them as black boxes so we can stay focused on the component we currently work on.

Many techniques, tools, libraries and programming language features are devoted to assist us in breaking our projects into components that are easier to work on. One of the principles to make it clear which part of the code is responsible for what.

Usually, you'll want the declaration of things(variables, constants, classes, functions etc.) to be responsible for defining what the thing can and can't do, and it is very helpful to get your tools to intelligently alert you when you misuse that thing. When you call sqrt(-18), it's nice to have a compilation error that says "you can't call sqrt with a negative number!". It's less nice, but still good, to have that error at runtime. You really don't want to get some weird output farther down because sqrt(-18) returned some random value because you used it wrong...

This is where constants fit in. They let you define at declaration that the value should not be changed at runtime, and that definition is enforced at usage. So if some developer thinks they can change it's value - the compiler will yell at them.

Now, no one in their right mind would change the value of PI, but other values may appear modifiable even when they aren't. Making them constant means their maintainer is not going to support the implications of changing them at runtime, and forbids other developers from changing them.

BTW - I keep referring to "this developer" and "other developer", but they can be the same developer. Since you can't keep the entire structure of the program in your limited human mind, when you work on another component you might as well be another developer because you've changed your context.

0

One of the main reasons for constants (in particular compiler constants) is to give a consistent value for a predefined thing (i.e., pi, e, null, etc.).

Constants are also time saving. I don't have to look up the values when I need to perform certain types of math.

0

In some programming languages calling something a constant is a way to mark it as immutable. Using your example of PI you could define a variable called PI and assign it 3.14 and use that throughout your code as the value of PI. However, what happens when some later programmer using your code decides that their code needs a more precise representation of PI and they set your PI variable to 3.141592. That MIGHT not cause an issue if your existing code can handle the added precision or it might break everything in some weird way like rounding it off to 3.1416 (which is most definitely NOT PI).

1
  • 2
    Eh. 3.1416 may not be Pi, but it's a lot closer then 3.145, which also isn't Pi. Drop the sarcasm and you have a half decent answer. You're the only person I've seen mention immutability. No one's mentioned that constants are calculated at compile time, rather than runtime either though. – RubberDuck Mar 22 '16 at 0:10
0

To expand on @Robert Harveys answer

  1. A lot of compiled languages embed constants in the compiled code, so there is a compiler/interpreter level reason
  2. 3.14 as PI means something to the outside world, but it doesn't necessarily mean anything in your programs' world (or domain) until you add it as a constant. Think of your program as a person; the more things you tell it, the smarter it gets.
2
  • 3
    Could you expand on #5. – JeffO Mar 22 '16 at 15:52
  • For example in .Net, if you have {const string MyConst = "Hello";}, then the variable MyConst is compiled as a part of your assembly and will live in the area of memory which your application code (.dll files) lives. If you use any other assignment operator, then the value of MyConst will not be calculated until run time and will live in the area of memory which your application state (objects and variables) live. This may have been important in the past, but it is not particularly relevant now unless you want every last CPU tick to count. – Shane Mar 25 '16 at 20:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.