# C++ Notes: Programming Guidelines

This is a list of a few things that I think are important. There are a lot more, but this is a start.

## Readability vs Efficiency

Assuming a program executes correctly, the single most important thing is readability. Efficiency is secondary to readability, but it's important to avoid gross inefficiency. Some of the factors that will be used in evaluating a program follow.

## Naming

Names are extremely important in making a program readable.

- Choose meaningful names when possible. Certain common names are ok (i as in iteration variable), but generally they should describe their contents.
- Avoid confusing names. Eg, formal parameter named the same as actual parameters is misleading, don't shadow outer names, names shouldn't differ only by case, etc.

## Indentation, comments, spacing, ...

- Indentation is important. Use 3, 4, or 5 spaces; 4 is recommended.
- Comments at the beginning of every file should identify the program, the author, and give the date.
- Program sections should be separated (like paragraphs).
- Don't comment obvious things. If something is not obvious it should be commented. Every function should have at least a one-line comments. Declare variables one per line so that the remainder of the line can be used for comments.

## General coding

- DRY principle (Don't Repeat Yoursefl). If you need to reuse a section of code, don't cut-and-paste it. Instead generalize it with a function or loop. If it's in both the true and false clauses of an if, factor it out.
- Choose the most appropriate statement for the job. Yes, you can use switch instead of if, or write all loops with for, but don't do this.
- Don't reuse the same variable for more than one purpose. The cost in confusion is certainly more than the minor saving of a few bytes.
- Use standard C++ because I'll be using Dev-C++ to compile and test your programs. If you want to use non-standard libraries, clear it with me first.

## Functions

- In parameter passing pay attention to whether you should use reference and/or const.
- Functions should be coherent - do one thing. Don't combine multiple tasks in one function. The function they perform should be reflected in the name, which is typically a verb.

### C++ Standard

Avoid non-standard C++ constructions, even tho your compiler may allow non-standard usages.

- `main` should be int, not void.
- Don't use `#pragma`, it's not portable.
- It's really minor (and even stupid), but the standard requires a newline character at the end of source files. If you don't put one there, I see a warning message when I compile your program.