C Style Guidelines

Style Checklist

NOTE: There are code examples at the end of this page

  1. Meaningful names for variables, constants and functions. Do not use camelcase; use underscores for multi-word variables. For example, use hot_water_temperature instead of hotWaterTemperature. Using a variable name with a single character is only appropriate if the variable is the iteration variable of a loop; otherwise using a single character variable is not correct. For example, if a variable represents a sum, name it sum instead of s.
  2. Good indentation (3 or 4 spaces). Use a proper editor (e.g., emacs, vi) that assists with indentation.
  3. If variables have the same type, declare them on the same line if possible.
  4. Leave one blank line between variable declarations and the first line of code in a function.
  5. Consistent style (e.g., use of curly brackets).
  6. Opening brace must be on the same line as conditional or function.
  7. Define values as constants when needed (do not use variables for constants). Do not use numbers in your expressions if those numbers have a special meaning (e.g., 3.1415); instead define constants (e.g., using #define) for them.
  8. #defined constants must be in uppercase (e.g., #define MAX_LEN 10 and NOT #define max_len 10).
  9. In your code you should leave one blank space between operators (e.g., x = 5 + 7).
  10. Leave one space after a comma.
  11. If the code is too complicated to be read on its own, simplify/split/rename variables.
  12. Use braces; avoid loops and conditionals without them.
  13. Use parentheses for clarity, especially with bit operations.
  14. Avoid global variables where they are unnecessary.
  15. If p is a pointer to a structure, you should access members by using p->member rather than (*p).member.
  16. If p is a pointer to a structure, do not surround the -> operator with spaces (use p->id instead of p -> id).
  17. You should avoid source lines exceeding 80 characters. You can use the linecheck command in the grace system to verify you have lines with the appropriate length.
  18. Use the indent utility (after setting the alias as described in the grace info folder indent_utility_info.txt) and run it against a copy of your code. Compare the indentation generated by the utility and your original code.

Take a look at the examples below, so you know what we are expecting when it comes to style.

Regarding Indentation

For this course, make sure your indentation is OK in emacs. Graders will use that particular editor to verify you are using good indentation. One reason why indentation can look different in several editors is the tab settings.

Code Organization





Style Notes (Select the Link)

Additional notes can be found at style notes.