You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.8 KiB

Programming Style

Here we discuss a good programming style (formatting, conventions etc.). Remember that nothing is set in stone here, the most important thing is to be consistent and actually think about why you're doing things the way you're doing them.

This is "our" recommendation or perhaps just a suggestion/guide on the C programming style.

  • Use two spaces for indentation. Do not use tabs! Tabs are ugly, tricky non-standard behaving chars.
  • Formal to 80 columns or a similar width.
  • Write opening and closing curly brackets on the same level, e.g.:
if (a == b)
{
  doSomething();
  doSomethingElse();
}
  • Prefer not writing curly brackets if you don't have to (e.g. with a single command in the block). You may still do it in tricky cases like nested branches.
  • naming:
    • camelCase for variables and functions (like myVariable). Global and big-scope variables should have a descriptive, self-documenting name (e.g. getTicksSinceStart), local/short-scope ones can be just one letter.
    • CapitalCamelCase for data types (like ImaginaryNumber).
    • ALL_CAPS_SNAKE_CASE for macros (like PI or MIN).
    • It is advised that for your project you come up with a three letter namespace prefix that will come in front of your global identifiers. (E.g. small3dlib uses the prefix S3L_). If you choose a prefix XYZ_, put it at the start of every global identifier, it will prevent name clashes and help readability.
    • Prefix private global identifiers with _, e.g. _myInternalVar.
  • Use spaces to make code more readable, so e.g. int x = 10, y = 20; instead of int x=10,y=20;, write space between if and its condition etc.
  • Use blank lines to logically group relevant lines of code. E.g.:
int a = x;
char b = y;

c += 3 * a;
d -= b;

if (c < d)
a = b;
  • Each file shall have a global comment with at least: short description of the file's purpose, license, the author(s) and year of creation.
  • Use comments to make your code better readable and searchable (add keywords to relevant parts of code etc.).
  • Don't use enums, use #defines.
  • Global variables are great, use them. Long functions are fine.
  • Adhere to C99 standard. You may consider adhering to C89 standard for even better portability (i.e. no declarations in the middle of the code etc.).
  • Try to not create many source files, many times your project can very well be in a single file which is the ideal case. If you have multiple files, keep them in the same directory and try to have just a single compilation unit (only one .c file with several .h files). Try to make files no longer than 10k lines.
  • Do not use non-ASCII characters in the source code.