Dr. Janzen's C Code Style Guidelines
Students should use the following Code Style Guidelines
for all programs they write in this class. This style is based on
the K&R code style with no tabs.
- Function and Variable Names
- Choose meaningful identifier names such as numTacos, not x.
- Do not use underscores unless directed to do so in a project description.
- Multi-word names should capitalize the first letter of the second and later words (e.g. getSize, sumOfInputs).
- Data types should capitalize the first letter of the first word also (e.g. State).
- Constants should be all capitalized, separating words with underscores (e.g. NUM_STUDENTS).
- Indenting
- Indent each level five spaces.
- Do not use tabs.
- Open braces ("{") go at the end of the line of control flow commands (e.g. if, while), while the closing brace ("}") goes at the beginning of the last line of the block, lining up with the start of the initial command.
- Open braces for functions go at the beginning of the first line of the function body block, and close braces match indentation at the beginning of the last line of the function body block.
- Open braces should be coddled on the same line after else.
For example, the following is correct:
int main(void)
{
int numTacos;
if (numTacos > 0) {
doSomething();
doSomethingElse();
} else {
doSomethingElseElse();
}
return 0;
}
- Spacing
- Lines should never be more than 80 characters wide.
- If a line is longer than 80 characters, break it in two and
indent the second line.
- Functions should not be more than about 50 lines long.
- Files should not be more than about 500 lines long.
- Blank lines (only one) should separate logical blocks of code.
- Insert one blank line after local declarations in a function.
- Spaces should separate:
- operators and operands (e.g.
3 * 4
, x <= 0
),
except the operators [], ++, &, and * when used to to indicate a pointer
- commas and the following word (e.g.
doIt(int a, int b)
)
- semicolons and the following word in for header (e.g.
for(int i=0; i < 4; i++)
)
- Comments
Automatically Applying Code Style
Before you turn in a program, you should use the following command on vogon:
indent -kr -nut your_program.c
You can read about the indent program online or by typing man indent
on vogon.
The indent command will make a copy of your_program.c to your_program.c~
before making changes to your_program.c.