C Program

Style Rules

 

Copyright 2006 Dr. Clinton Staley

cstaley@calpoly.edu

 

The following style rules are mandatory for all programs submitted.  Breaking a style rule will cause your program to “bounce”, and you will have to redo the code according to correct style.

 

1. Identifier names 

B. Choose variable and type names carefully.  X, jj, and b2 don't mean as much as timeLeft, biggest, and whereNext Variable names should be meaningful, and generally not single-letter.

 

C. If you decide to abbreviate a commonly used term in variable or type names, use exactly the same abbreviation everywhere.  (For instance, if the term "category" appeared often in variable or type names, you might abbreviate it everywhere to "ctg".)

 

D. In multiple-word names, capitalize the first letter of the second and later words.  Do not use underscores.  In names of functions, types, and global data, capitalize the first letter of the entire variable name, too.  Leave the first letter lowercase in locals and parameters.

 

Functions, globals, types:  String   ClearList  TotalSize

 

Locals and parameters: stringLength  nameNdx  bestScore

 

E. Do not use “Hungarian notation”. 

 

2. Constants

Use constants.   There mujst be no actual numbers other than 0, 1, -1 or 2 in your code.  Even these might sometimes be constants if they could change in later versions of the code.  Use all caps for constants, and underscores to separate words in this case. 

 

3. Global Variables

Never use a non-const global variable without first asking me.  And if you ask me, I will say “No.” 

 

4. Function Design

Functions must be at most 50 lines long, not counting blank lines, assertions, or lines containing only a single brace.  Don't cram code to satisfy this limit.  Break up your functions instead.  Functions with long switch statements or if-else blocks are an exception to this rule.

 

 

 

 

 

5. Indentation and Blank Lines

A. Use 3 space indentation, and indent only one level for each nested  if, while, or switch.  Do not use tabs for indentation.   Hidden tabs are one of the most common sources of style bounces.  You may want to use the "detab" program from my ~cstaley/bin directory.

 

   while (...) {

      statement;

      if (...) {

         statement;

      }

   } 

 

B. Never let a line exceed 80 columns.  If a line must be broken into two, indent the second part one space past the first column of the first part:

 

       Big long line....

        with continuation line below

 

C. Indent both the then and else blocks of an if-statement, even if  they are only one line long.  Don't write: if (test) statement;

 

D. Use blank lines to break up blocks of code.  Code should fall into groups of about 5 lines on average, separated by a blank line or a line with only a brace.  Always put a blank line after the local declarations in a function.   Don’t put more than one blank line in a row.  A single blank line at a time is enough to break up the flow of code properly.

 

E. Place the opening brace at the end of the first line of the if, while, struct, etc. that it applies to.  (See examples under 6A and 11.).  The only exception is the opening brace of a function, which goes on a line by itself.

 

 


6. Large Scale Organization

A. Files should be at most 600 lines long.

 

B. Include files must be protected by #ifndef/#endif pairs to avoid  multiple inclusion. 

 

C. Files must come in .h/.c pairs, with each pair defining some group of related functions.  Do not cram declarations, constants, and prototypes into a big, general purpose, .h file.

 

D. If a declaration is needed in only one .c file, don't put it in a .h file at all -- include it in the .c file that needs it.

 

7. Horizontal Whitespace

Use whitespace to clarify your code and to break up long expressions, but don't overdo it.

 

A. Put spaces after each comma, and around each keyword (note that "if", "while" and "for" are keywords).  Put a space after each semicolon in a for header.  Never put a space before a comma or semicolon.

 

B. Put spaces around operators, except for operators on the top two rows of the precedence table (e.g. [], ++, &) or in very large expressions where you may avoid spaces around the innermost operators.  Don’t have more than three variables or operators in a row without a blank space.

 

Good:  epsilon = 2*beta[1] + *gamma - delta*pi;

Bad:   epsilon=2**gamma-delta*pi;

 

C. Put single blank lines after each function, and between local declarations and the function code. 

 

D. Don't put space after an opening paren, or before a closing one.  Do not put space between a function name and the opening paren for the parameter list.

 

 

8. Comments (when required for the assignment)

Be sure the main file includes a comment giving your name, and section number if you're in a multi-section course.

 

Add declaration comments to each header file.   Declaration comments describe the functions or types declared in the header.  Declaration comments describe only the interface, not implementation details. 

 

Add implementation comments to each source file, describing how each function in the source file works.  Do not repeat information from the declaration comments in the implementation comments; stick strictly to describing the implementation.

 

Don't comment the obvious; concentrate on explaining the hard parts.  Put variable, type, and function names in quotes in comments, to distinguish them from ordinary words.  Any time a method or implementation is changed, the comment must be changed as well.  Keeping comments current is essential to their usefulness.  If comments frequently are out of date, people start to ignore all comments.

 

Comments must be clear.   A set of words in comment markers is not automatically a comment.  If the comment isn't clear,  it doesn't exist.  Comments must be perfectly spelled, and perfectly grammatical.   We routinely bounce programs for grammar and spelling errors.

 

Most professional programmers do not like to see comments intermingled line-by-line with code, since this distracts their eye as they read the code.  Put comments in function headers, not in the code itself.  You may mark a line with a number thus: // 1 , and discuss it in the function header.  On rare occasions you may add a short comment to the right of the code to explain something especially confusing.

 

9. Code Safety

The following rules will help eliminate coding errors, or make them easier to catch:

 

A.  Use assertions to check input assumptions on functions and to check the outcome of complex blocks of code.  Assertions should only be used to check for bugs in the code, not to cover user or file format errors.  Use exceptions for these.   Write an assertion only if you would change the code in the event of the assertion’s failure.  As a rule of thumb, you should have 3-8 assertions per page of code.

 

B.  Always add a “default” case to a switch.  If this case should never be reached, then place an “assert(0)” in it.


10. Style Examples

Example of Good Style:

 

int Test(int number)

{

   int count;

 

   for (count = 1; count < MAX; count++) {

      if (number+1 > i && number-1 < count) {

         printf("hello\n");

      }

      else {

         printf("goodbye\n");

      }

      number = number + 1;

   }

 

   count = number;

   while (count > MAX)

      count = count - DECREMENT;

}

 

Example of Bad Style:

int test(int n) {          <-- lowercase name, and { on same line

   int i;                  <-- one letter name, no space after locals

   for (i=1;i<5;n=n+1,i++) <-- bad horizontal space, use of constant       

   {                       <-- belongs on prior line

      if (n+1>i && n-1 < i) <-- Single letter variable names.

/*********************************  <-- Dumb banner comment

 *  This is an if statement !    *

 *********************************/

         {                 <-- Double indentation

            printf("hello\n");

         }

      else {            

            printf("goodbye\n");

         }

   }

   i = n;

   while(i > 10)           <-- no space after "while", use of constant

      i = i - 2;

}