How to Avoid Introducing Errors in C++ Programming
The easiest and best way to fix errors in C++ is to avoid introducing them into your programs in the first place. Part of this is just a matter of experience, but adopting a clear and consistent programming style helps.
Coding with style
Humans have a limited amount of CPU power between their ears. You need to direct what CPU cycles you do have toward the act of creating a working program. You shouldn’t get distracted by things like indentation.
This makes it important that you be consistent in how you name your variables, where you place the opening and closing braces, how much you indent, and so on. This is called your coding style. Develop a style and stick to it.
After a while, your coding style becomes second nature. You’ll find that you can code your programs in less time — and you can read the resulting programs with less effort — if your coding style is clear and consistent. This translates into fewer coding errors.
When you’re working on a program with several programmers, it’s just as important that you all use the same style to avoid a Tower of Babel effect with conflicting and confusing styles. Every project needs a coding manual that articulates (sometimes in excruciating detail) exactly how an if statement is to be laid out, how far to indent for case, and whether to put a blank line after the break statements, to name just a few examples.
C++ doesn’t care about indentation. All whitespace is the same to it. Indentation is there to make the resulting program easier to read and understand.
Establishing variable naming conventions
There is more debate about the naming of variables than about how many angels would fit on the head of a pin. Use the following rules when naming variables:
The first letter is lowercase and indicates the type of the variable. n for int, c for char, b for bool. This is very helpful when you’re using the variable because you immediately know its type.
Names of variables are descriptive. No variables with vague names like x or y. You need something that you can recognize when you try to read your own program tomorrow or next week or next year.
Multiple word names use uppercase at the beginning of each word with no underscores between words.