A Simple Style Guide for C Programmers

Writing a program is not a private conversation between you and your computer, it is to be read by people ... you, your coworkers, the people who will maintain it, the people who replace you, etc. Here are some of the most basic stylist rules used by professionals:
  1. Indent 3 or 4 spaces (pick one). If your editor doesn't do this automatically for you get a better editor.
  2. If your indenting is over 4 levels deep then make the deeply indented code a procedure.
  3. Use blank lines between groups of lines of code that have a common purpose. In every 10 lines of code there should be at least one blank line.
  4. Use at least two blank lines before a procedure.
  5. Put a comment block before every procedure even if it is only a couple of lines.
  6. Always put a space after a comma.
  7. Never write a procedure in procedureal language that is more than a page long.
  8. If procedure calls are of the form procname(args) then there should be no space between the procname and the opening paren.
  9. If there is a keyword followed by an opening paren allowed in the language then there should be a space between the keyword and the paren as in: while (
  10. In C try to hide opening braces and expose closing braces.
    	if (test(y)) {
    	    stmt1;
    	    stmt2;
    	}
    
  11. An opening brace should always be preceeded by a blank.
  12. If you have a single statement after an if or looping construct and you don't provide a separate block for it (such as using braces in C++) then put the single line right after the if.
     
    	if (test) x = func(y);
    
    not
     
    	if (test) 
    	    x = func(y);
    
  13. Use meaningful variable names. Trivial counters and temporaries can be single letters but the rest should have meaning. Bad variable names include things like x, thx1138, blah, and stuff.
  14. Avoid mixing declarations and executable code in the middle of blocks. Move declarations to the beginning of blocks when possible. If this moves the declarations away from the scope of use then create a block specifically for defining the scope of the declarations. (This is part of the good programming practice of avoiding multiple meaning or use for a single statement/variable etc.)
  15. Avoid just pasting cloned code around in a program, when a procedure can be created and duplicate code removed. Only do this if it is logical.
  16. Apply these rules consistantly throughout your program. You lead a reader into your style. Don't change it on them midstream.