C-Style Guide


All C-style code, C, C++, JavaScript, etc. must conform to industry standard formatting guidelines. You may select from either K&R or Allman style, while also making sure to conform to universal standards (listed first).


Universal standards for C-style code.

Applies to all code regardless of the specific style you choose.

  • 4 spaces per indent level (no tabs). Note that this does not refer to whether or not you press the tab key, but to what happens when you do. You should configure your IDE to insert 4 spaces when you press the tab key.
  • Do not break lines in the middle of statements unless a statement is too long to fit on one line, which is defined as 80-characters. In that case, break it up a logical points such as after an operator or comma, and indent the continuation line(s) to align with the start of the statement.
  • Use spaces around operators and after commas, but not directly inside parentheses. For example: if (x > 0) { is correct, while if(x>0){ is not.
  • All code blocks must be enclosed in braces, even if they contain only a single statement.
  • Never combine multiple statements on the same line. Each statement should be on its own line, even if they are simple or related.

The two specific styles below are both acceptable and are the most common in industry. You may choose either one for your code. The most important thing is to be consistent. Do not mix styles within the same project or file.

K&R Style (Kernighan & Ritchie)

This is the most common style in C and C++ code, and is also used in JavaScript. It is named after Brian Kernighan and Dennis Ritchie, who popularized it in their seminal book on C programming. In this style, the opening brace of a block is placed on the same line as the control statement, and the closing brace is aligned with the control statement.

    if (condition) {
        do_something();
    } else {
        do_other();
    }
                

Allman Style

This style is named after Eric Allman, who used it in the original Sendmail code. Also known as "BSD style," it is commonly used in Windows programming and some open-source projects. In this style, the opening brace of a block is placed on a new line, and the closing brace is aligned with the control statement.

    if (condition)
    {
        do_something();
    } else
    {
        do_other();
    }