Wednesday, October 15, 2008

C++ Coding Standard: Other Stylistic Issues

I can't believe it! The last section of the C++ coding standard. Mostly these are issues of clarity, readability, or grep-ability.
  • 12.1. Mark 64-bit constants "LL" or "ULL", e.g. 0xffffffffffffffffULL.
  • 12.2. Mark 32-bit constants >= 0x80000000 "U", e.g. 0xffffffffU.
  • 12.3. Use C++-style typecasts instead of C-style typecasts.
  • 12.4. A source file must not include tab characters (only spaces).
  • 12.5. Lines must contain no more than 80 characters, including the (invisible) newline character at the end.
  • 12.6. A source line must not contain two statements.
  • 12.7. Use 2 spaces per level of indentation.
  • 12.8. Indent the body of a compound statement ("if", "while", etc.) one level more than the head of the statement.
  • 12.9. An "else" must have the same indentation as its "if".
  • 12.10. Two statements in a sequence must have the same indentation.
  • 12.11. A comment is indented the same as the statement following it.
  • 12.12. No character must appear to the right of a brace ("{" or "}").
  • 12.13. A closing right brace must be indented to the same level as the line containing its corresponding left brace.
  • 12.14. There must be no space between the function name and the left parenthesis of a function call (e.g. "printf(...)").
  • 12.15. There must be a space between a keyword and a left parenthesis (e.g. "if (x != NULL)").
  • 12.16. Do not use C-style comments (except for documentation comments).
  • 12.17. Do not comment out or "#if 0" dead code. Remove it.
  • 12.18. Do not use external include guards.
Everyone has an opinion about where the braces go on if, while, etc. I try to avoid religious battles like that, and allow you to put the opening brace on the same line or the next line, as you wish. However, 12.12 does prohibit the despicable Tcl style of "} else {". Code is much more readable if the else lines up with the if. The same reasoning leads to 12.13: line up the closing brace with the line that opened it. This works no matter where you put the opening brace.

Of course 12.7 can be tailored to suit your needs: I chose 2 because I think less is more when it comes to indentation. However, 12.4 is absolute. Tabs mess everything up.

Although this section is mostly about style, there is a practical reason for 12.6. The effectiveness of measuring line coverage is diminished if there can be more than one statement per line.

No comments: