The standards here will be used in the rubrics for assignment submissions. The rubric will be the final authority, not this document.
There are many coding standards, not just for C, but for most languages. If your only exposure to languages is python, it can be said that most python follows PEP8 or it's replacement, and thus looks similar.
The rationale behind coding standards, is to make the code easier to read by all programmers following the standard. For that reason, code must be formatted using the following sets of guidelines.
-
Documentation
/** <filename.c> * Submitted by: * Student #: * * This code is ... <solution to|performs|can be|etc.> * */
-
Include Statements
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include 'localfile.h'
-
Global Variables
int sum; float average; <type> <variable name>;
-
Function Prototypes
int calculate_average(int *numberlist, int number_values); int print_values(void);
-
Main function
int main(int argc, char *argv[]) { /* Body of main function (starts with declarations) */ }
-
Function Bodies
int calculate_average(int *numberlist, int number_values) { /* Body of function */ /* return statement */
Formatting should follow K&R style, sometimes called "one true brace style" or other names. Of primary concern is that formatting be consistent, with consistent indenting for code in the same block. Use of the format command in Visual Studio Code is highly recommended. If you have access to 'clang-format', I would recommend setting it up in VS Code as the formatter (but the built in formatter is sufficient).
-
Return type is on the same line as function name.
-
Arguments are on the same line as function name
-
Opening brace is on the same line as function name
-
Closing brace is at the same level as return type for function
int main(int argc, char *argv[]) { /* Body of main function (starts with declarations) */ }
- Operators have spaces. For example:
=
or+
int value = 3;
value = value + 5;
- if statement has an opening brace even for one statement
if (value == 8) {
printf("Yay\n");
} else {
printf("Boo\n");
}
- loops and other blocks of code should have one blank line after the block
for(int i = 0; i<MAX_VALUE; i++){
printf("Value is: %d\n", i);
}
result = (expression);
-
Snake case sometimes called pothole notation. You can find examples at the following links
-
Variables and functions should start with a lower case letter, for example:
-
Function prototype:
float celsius_to_fahrenheit(float celsius_value);
-
Variable:
char *course_name = "COMP2004";
-
-
Constants should be all upper case, but use the underscore separator between words (pothole notation). For example:
-
Pre-processor:
#define CELSIUS_FREEZING 0
-
const float KELVIN_FREEZING = 273.1;
-