Why is the use of a constant considered better programming style than the use of a literal? What is the exact advantage of the prior over the latter?
One reason is to assist in maintenance. Let's say you're stuck in the dark ages and your graphic manipulation program works only with 1.4M floppy disks.
You get a request to handle the new-fangled 2.8M floppy disks and you think to yourself "Ha, I just need to search through the code looking for 1440 and replacing that with 2880. Simple, eh?".
Unfortunately, being a graphic program, 1440 is also the number of twips in an inch, so you find that after doing your massive global search and replace, not only can you handle the larger disks but all your images are the wrong size on the screen. D'Oh!
Now you have to go back and figure out which of those 1440
strings were for the disk size and which were for the image size.
If you had just developed your code like this:
#define TWIPS_PER_INCH 1440
#define DISK_SZ 1440
you could have made the change much easier, by just changing that constant in one place without affecting all other constants with the same value.
Short answer is that named constants make your life a lot easier. That really should be reason enough for using them.
Some extremists will insist that the only hard-coded constants you should ever have in your program are -1, 0 and 1 - some will go even further but we can discount the crackpots :-) I'm not quite to that point but I do think it's a good idea to avoid them as much as possible.
One thing I find amusing is people who do things like:
#define SEVENTY_TWO 72
I'm not exactly sure what they think they're gaining by that but I actually got that once in response to a comment I made in a code review about the hard-coded 72
(I can laugh about it now but I was none too happy in the second review meeting).
Another reason is to make the code more readable. Unless you have a mathematical background, you're going to be at a loss when you see a constant like 1.414
in your code. However, the symbol SQR_ROOT_OF_2
is likely to be much more understandable. It's the same with most other constants, like:
SECS_PER_DAY 86400
CUST_ADDR_LINES 7
INVALID_ID -1
DAYS_PER_CENTURY 36524
PASS_LEVEL 63
MIN_REPUTATION 10000
MAX_LOAN_AMT 200000
Would you rather have code with those numbers on the right scattered throughout, or would you rather read code where the intent is better presented?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With