Comments make it easier for us to grade and understand your code. Comments about the functionality of each function go in the header files. You should add comments to your .c files that help us understand your implementation.
Proper use of whitespace can greatly increase the readability of code. Every time you open a block of code (a function, “if” statement, “for” or “while” loop, etc.), you should indent one additional level.
You are free to use your own indent style, but you must be consistent: if you use four spaces as an indent in some places, you should not use a tab elsewhere. (If you would like help configuring your editor to indent consistently, please feel free to ask the course staff.)
Give variables and functions descriptive but concise names (e.g.,
semaphore_foo() instead of
Dead code is code that is not run when your program runs, either under normal or exceptional circumstances. These include “printf” statements you used for debugging purposes but since commented out. Your submission should have no “dead code” in it.
Make your code “fail early”, i.e., check for nullpointers, negative
indices, and so forth. Use
assert to check invariants for
correctness. Keep in mind, however, that asserts are largely for the
programmer’s benefit, not the user’s. If you are writing a function
that provides a service to a user, returning an error message is a
much more graceful and helpful way to respond than to fail an assert
Magic numbers are numbers in your code that have more meaning than simply their own values. For example, if you are reading data into a buffer by doing “fgets(stdin, buf, 256)”, 256 is a “magic number” because it represents the length of your buffer. On the other hand, if you were counting by even numbers by doing “for (int i = 0; i < MAX; i += 2)”, 2 is not a magic number, because it simply means that you are counting by 2s.
Magic numbers make your code hard to read and correctly update. You should use #define to clarify the meaning of magic numbers. In the above example, doing “#define BUFLEN 256” and then using the “BUFLEN” constant in both the declaration of “buf” and the call to “fgets”.
Many choices are up to you (for example, where the curly braces go, whether one-line “if” statements need braces, how far to indent each level). It is important that, whatever choices you make, you remain consistent about them. Nothing is more distracting to someone reading your code than random style changes.
Parts of this style guide were originally written as “Code Style” for the CMU course Intro to Computer Systems. Parts of it were home grown in the brains of your instructors and teaching assistants here at Cornell.