1

In the lectures and the walkthroughs for Week 2, David goes through a capitalize program. He makes a point of using the subtraction 'a'-'A' rather than simply the value 32 in order to change the case of the input. I presume the reason is merely to show that you don't need to remember that it's 32, you can just get the computer to calculate it. Is this all there is to it? Or is there some other reason/advantage in doing this?

2

If there's a deeper lesson here, its to avoid using "magic numbers".

Programs are meant to be readable by programmers, which is why we use languages like C instead of writing binary. Using hard numbers in the program code makes it harder to understand what the programmer intended when the code was written.

Programs use all kinds of numbers which are meaningful when interpreted in some context, but pretty meaningless when written just as a number. As an example the number 65 means the same as the letter A when interpreted as a character.

To put this into an example. If the number 65 is used in the code, a programmer reading the code will have a much harder time trying to figure out what the program is supposed to be doing. Compared to seeing the value A, which can immediately be identified as a character. If the code had a bug and the programmer mis-typed the number as 66, it's much harder to tell if the value is correct.

This principle can be extended to any numbers used in code. Any time you find yourself entering a sequence of digits, or a string, or anything which isn't actual syntax, ask yourself if you can rather use a constant or a named variable or function. Doing so documents your code making it easier to read and maintain.

0

No, just that, and also to remember that in C, chars can be used as char or as an int.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .