Best Practices For C Code
Best Practices For C Code
Best Practices For C Code
One of the expectations of this course is that you will employ the best
practices for C code we discuss in class when writing your own programs.
The details are provided below, and comprise one of the homework rubric
assessment criteria. Items may be added to this list as the course
progresses.
Best Practices
General
o Use the simplest code necessary to accomplish a task.
Avoid unnecessary complexity.
o Eliminate unnecessary code (that which performs no
meaningful task).
o Eliminate duplicate code (performs the same test,
operation, function call, etc. as other code).
Variables
o Variable names must start with a lowercase letter.
o Variable names must be meaningful and descriptive.
o Do not use the data type in the variable name.
o Each variable must be declared on its own line.
o Each variable must be initialized when it is declared.
o All variables must be declared at the beginning of the
function, before executable statements.
o All variables must be declared inside a function. Global
variables are prohibited.
Operators
o Incrementing or decrementing a value by one must use
the appropriate self-operator (++, --).
o Always use the arithmetic assignment operators [+=, -=,
*=, /=, %= ] in place of the long form
e.g. use sum += num; not sum = sum + num;.
Constants
o Do not use "magic" numbers.
Example: if (letter >= 65 && letter <= 90);
instead use human-recognizable literals: if (letter
>= 'A' && letter <= 'Z')
Example: int array[32]; instead use a #define:
int array[MAX_ARR_SZ];
o #defines must be written in all CAPS, with optional
underscores.
Example: #define MAX_ARR_SZ 32
Loops
o Work that can be done only once, must not appear inside a
loop. (It should be done before or after the loop).
o You must use a for loop, not a while loop, to iterate
through an array.
Functions
o Functions must not duplicate work, when the same work
can be done by calling another function.
o The keyword void must be used to indicate no return value
or an empty argument list.
o If a function has no return value (void), there must be no
return statement in the function.
o Function arguments that are pointers must be checked
for != NULL before using.
Comments
o Individual comments should be used to elaborate on the
purpose of a variable, or to explain a complex section of
code.
o Do NOT use a comment which simply restates what the
following line of code is doing.
Readability
o There should not be pervasive spelling errors in your code.
Disallowed Practices
The use of the break and continue keywords in loops is not allowed.
The use of the goto keyword is never allowed.
The use of C string library functions is not allowed.
The use of C language features we have not discussed in class is
discouraged. If you use them incorrectly, it will be considered a
best practice violation.
The use of global variables is not allowed.