If you are already familiar with constants, then just go away! Then this article is not for you! This is a bit of beginner’s stuff, or just a tip for “cleaner code”.
I do remember that I have been teaching people Pascal in a long distant past. Pascal is a language that takes pride in a very extensible constant system. Much other languages supporting constants have a less extensible system, but still a constant system, and C coders may even be using macros in the same kind of manner that constants are used in other languages (although modern C compilers should support constants as well).
Some languages (like Lua) do not have support for them at all and some older versions of BASIC do neither.
My apprentices never fully understood why constants serve a purpose.
I’ve recently been following some training in JavaScript and I was very heavily relying on constants in some assignments I got, and my teacher praised me for doing so (as not all of my fellow students did).
In a basic rule constants and variables are ALMOST the same, with the big difference that variables can be modified whenever you want to where constants can only be defined once and never be modified again.
Of course, why one needs variables in obvious. If you ask the players name you use a string variable (or a char* variable if you are using C). You can use integer variables starting on 0 and counting up every time the player does something well, and thus generating a score.
But why constants?
If you ask me if they are needed, I can answer simply… no! Any programmer should be able to live without them. However, there are still many reasons to use them.
Now this is a simple example in Pascal. Imagine you are following a training in Pascal and the teacher asks you in a triangle ABC in which B is 90 degrees, and AB=20 and BC=40 to make a Pascal program that will calculate AC by using the Pythagorean Theorism.
Well since that would be AB^2 + BC^2 = AC^2 you may do it like this:
Program Calc_BC;
Begin
WriteLn ( sqrt( (20*20) + (40*40) )
end.
Now I did not use power to make overstate things a little to point out making this clear. Now if the teacher says that if AB is not 20 but 25 now, you gotta replace two instances.
A true programmer is lazy. Why change two when you can only change one?
Program Calc_BC;
Const
AB:Integer=20;
BC:Integer=40;
Begin
WriteLn( sqrt( (AB*AB) + (BC*BC) )
End.
Now things are easier, eh? Just edit one 20 and the entire program keeps working. In the example above I only used 2 instances of each constant, but how about really complex programs that use the same value over say 40 times? Do you want to change them all 40 manually? Of course there’s a replace all feature in most IDEs, but here’s the rub: It is possible the same value also occurs in an unrelated instance and did therefore NOT need to be changed. OUCH! The replace routine won’t tell the difference… Crap!
Especially in calculation assignments I’ve used constants a lot for this very purpose. Since you can’t accidentally change them in runtime, they can be quite safe for these purposes.
Another reason why constants can be used is when you are using 3rd party libraries. They often come with constants rather than values for flagging some things. When you have a good compiler, the constants will just be handled the same as when you used values in stead, so what is the point then? Well, let’s say we got a simple graphics engine only using 5 colors.
red = 1
green = 2
yellow = 3
blue = 4
black = 0
Now here it comes, these numbers could be picked depending on some drivers the coder of that library used, but what if that driver is discontinued and the coder of the library decided to use a different drivers but was forced to change all color numbers as a result?
blue = 1
green = 2
red = 3
yellow=4
black =0
Yeah, I guess you get where I’m going, compiling your program again can lead to funny results if you used the values in stead of the constants.
When looking at the example above there is yet ANOTHER reason to use constants in stead of values. It is not usual that your code needs to be reviewed by others. Some of them not nearly as skilled as you are, but even when they outrank you “SetColor(1);” is not easy to read as “SetColor(blue);”. So by using constants you may need to type more sometimes, but it can be for the better some times. Also for yourself. Imagine when you haven’t touched your code for years and you suddenly discover a bug that needs fixing…. Having to study your own code can be time consuming, you know.
Avoid overkill, though.
Of course, there’s also such a thing as overkill.
I mean, I don’t feel THIS is needed:
Program Overkill;
Const
H1:String='Hello';
H2:String=' ';
H3:String='World';
H4:String='!';
Begin
WriteLn(H1,H2,H3,H4)
end.
I mean, this will then suffice:
Program Hello;
Begin
WriteLn('Hello World!')
end.
Still, sometimes even stuff that is only displayed once is often put in constants, like meta data.
Program MyProgram;
Const
Author:String='Jeroen P. Broks';
CopyrightYear:Integer=2018;
Version:String='1.0.0';
License:String='GPL v3';
Begin
<< CODE >>
End.
Very likely this data is only shown when people ask for an “about” overview, yet it is quite common to use constants for this.
Now Lua doesn’t support constants. Should I now use variables and pretend them to be constants?
The simplest answer would be yes!
One trapdoor though, this can take a tiny bit of extra memory, and Lua will still be able to modify these variables, so you should take that in mind.
What is better in C? Macros or the const keyword?
The danger in Marcos is that anything goes for a macro name, even C keywords can be overwritten this way.
However not all compilers understand the const keyword, and that is why most C coders prefer macros.
Of course when it comes to memory there can also be discussions:
#define N Jeroen
int main(void){
printf("My name is N and has always been N and will always be N");
return 0;
}
will become:
int main(void){
printf("My name is Jeroen and has always been Jeroen and will always be Jeroen");
return 0;
}
Not sure if the same goes for constants… :-/
Now you’ve seen why many languages support constants (and why I miss them in Lua). It is (of course) up to you if you want to use them or not. Trust me when I say that when I first coded in Pascal I also thought I had no use for them, but I’ve seen the light… ;)
Trapdoor in modern languages
A trapdoor in this (particularly important in JavaScript) is that most modern languages only store pointers in variables themselves when dealing with anything that is neither a number or a string.
const name = { myname:"Jeroen" };
console.log(name["myname"]);
name["myname"]="Jeroen P. Broks";
console.log(name["myname"]);
The code above is JavaScript specifically set up for NodeJS (you may suffer the same when this code is used in a browser, though). Despite name being a constant name[“myname”] did change. That is because only the pointer to the memory address of this table is being stored and only that can never be changed after its initial definition. The contents of the table itself are a different matter.
This however will NOT get anything changed:
const myname="Jeroen";
console.log(myname);
myname="Broks";
console.log(myname);
Based on how JavaScript has been configured this may even throw an error.
There are ways around this, but may be for a more advanced article. ;)
0 comments