Page1 ECE 341 Coding Standard Professor Richard Wall University of Idaho Moscow, ID 83843-1023 rwall@uidaho.edu August 27, 2013 1. Motivation for Coding Standards The purpose of implementing a coding standard is to generate compute programs that are easily comprehendible and reduce the chances for errors through consistency and expectancy. Quality code is written for readability by other humans, not computers. Quality computer code is never cleaver or obscure. The complexity of a computer program should only be to the degree as required to implement the design functionality and performance. All software submitted for assignments for ECE 443 will conform to the following format. 2. General Rules 1 We will follow the ANSI C standards unless not supported by the Microchip MPLAB environment or the Microchip C32 compiler. a. Comments Comments can add immensely to the readability of a program, but used heavily or poorly placed they can render good code completely incomprehensible. It is far better to err on the side of too few comments rather than too many - at least then people can find the code! Also, if your code needs a comment to be understood, then you should look for ways to rewrite the code to be clearer. And comments that aren't there won't get out of date. (An inaccurate or misleading comment hurts more than a good comment helps! Be sure that your comments stay right.) That being said, good places to put comments are: a broad overview at the beginning of a module data structure definitions global variable definition at the beginning of a function tricky steps within a function b. Source File Organization includes of system headers includes of local headers type and constant definitions global variables 1 http://www.jetcafe.org/jim/c-style.html#ansi
Page2 static function prototypes functions c. Naming Conventions Names should be meaningful in the application domain, not the implementation domain. This makes your code clearer to a reader who is familiar with the problem you're trying to solve, but is not familiar with your particular way of solving it. Also, you may want the implementation to change some day. Note that well-structured code is layered internally, so your implementation domain is also the application domain for lower levels. Names should be chosen to make sense when your program is read. Thus, all names should be parts of speech which will make sense when used with the language's syntactic keywords. Variables should be noun clauses. Longer names contain more information than short names, but extract a price in readability The letters in named constants should all be in upper case. For example #define MAX_LOOP_COUNT 100. Seeing a named value if all upper case letters indicates that this value can never be on the left side of an assignment statement. The letters in named variables can be all lower case or a mix of upper and lower case if doing so aids in comprehending the code. For example, int dog, cat, rabbit; or int MyPets;. Under score marks can also be used to make both named constant and variables more readable. Boolean variables should be named for the meaning of their "true" value. For example if(error), the variable error indicates that something is incorrect. Procedures (functions called for their side-effects) should be named for what they do, not how they do it. Function names should reflect what they return, and Boolean-valued functions of an object should be named for the property their true value implies about the object. Functions are used in expressions, often in things like if's, so they need to read appropriately. d. Functions Functions should be short and sweet. If a function won't fit on a single screen, it's probably too long. Don't be afraid to break functions down into smaller helper functions. If they are static to the module an optimizing compiler can inline them again, if necessary. Helper functions can also be reused by other functions. However, sometimes it is hard to break things down. Since functions don't nest, variables have to be communicated through function arguments or global variables. Don't create huge interfaces to enable a decomposition that is just not meant to be. e. Indentation and Layout The MPLAB editor implements a tab as equivalent to 4 space characters. When copying code from one text editor environment to another, be certain the tab settings are consistent. Henry Spencer's Ten Commandments for C Programmers says:
Page3 Thou shalt make thy program's purpose and structure clear to thy fellow man by using the One Brace Style, even if thou likest it not, for thy creativity is better used in solving problems than in creating beautiful new impediments to understanding.- The Eighth Commandment 2 The style that we will use in ECE 340 / ECE 341 is: Return_Type Function_Name(argument_list) { int x; // scalar declarations WORD y=100; // Initialization at declaration allowed char *p; // pointer declaration float data[10]; // array declaration } x = 17; /* code */ f. Expressions, Statements and Assignments In the programming language C, assignments are expressions, not statements. C allows multiple assignments such as a = b = c = 0;. Also, C allows assignments within an expression such as the expression, for(i=0; i<max, i++). This expression has one assignment, i=0;, and two operators, i<max and i++. 1. All expression will execute a single purpose. Compound expressions are forbidden except in the sense of common usage. Permitted compound instructions: for(i=0; i<max, i++) while((a<b) && (c<7)) Forbidden compound instructions: a = b*7 +16, c = 0; 2. Precedence of operation: When in doubt encapsulate with parenthesis! 3. ECE 443 Course Program Format a. Program Header i. File name ii. Author, date iii. Description of purpose iv. Example: /* ************************************************************* * File Name: Example_1.c * Author: Richard W. Wall * Date: September 2, 2011 * Revised: August 27, 2013 * This program is designed to allow you to explore the software 2 http://www.lysator.liu.se/c/ten-commandments.html
Page4 * instrumentation and debugging tools available with the MPLAB * Integrated Development Environment (IDE). This program is written * using the style expected for all programs submitted for ECE 443 * Examples for passing data by value and by reference between * two functions are provided. ***************************************************************** */ b. Include files i. System header files are bracketed between < >. ii. Local project header files are written between " ". iii. Example: #include <plib.h> // Microchip MX32 processor definitions #include <math.h> // Compiler transcendental math functions #include <stdlib.h> // Standard library #include "CerebotMX7cK.h" // Processor configuration definitions #include "example_1.h" // Contains definitions and function prototypes c. System Definitions i. Defined constant names are to be written in using upper case only. ii. Example: #define INT_SIZE 4 d. Global variable i. Variable names are to use lower case. ii. Only variables that are required to pass data to or from interrupt service routines are permitted to be declared global. iii. Special function register registers are declared global by the system. iv. Example: const int int_size = 4; float Xavg; int Xmax; int B_array[MAX_ARRAY] = {0}; e. Functions prototypes i. All function prototypes are declared in a project header file ii. Example: /* ************************************************************** * File name: example_1.h * * Author: Richard W. Wall * Date: September 2, 2011 * Revised: August 27, 2013 * * This contains configuration for programming and operation with
Page5 * the MX7cK as well as defines and function prototypes **************************************************************** */ /* Example_1 definitions */ #ifndef EXAMPLE_1_H #define EXAMPLE_1_H #define ARRAY_MAX (int) 256 #define MAX_ARRAY 10 #endif /* Function prototypes */ void statistics(int n, int *, float *avg, float *mean, int *max, int *min); float arithmetric_mean(int n, int *array); float geometric_mean(int n, int *array); int minimum(int n, int *array); int maximum(int n, int *array); void function_run_counter(void); void random_array(int n, int *array); /* End of example_1.h */ Note: The indentation rules for #if / #endif constructs follow the same rules as for open and close braces. f. Function declarations i. All functions (except possibly main) must have a description block using this following format: /* statistics FUNCTION DESCRIPTION *********************************** * SYNTAX: void statistics(int n, int *array, float *avg, float *mean, int *max, int *min); * KEYWORDS: statistics, mean, average, minimum, maximum * PARAMETER1: int - The input array size * PARAMETER2: int pointer -Address of integer array of data on which * the statistics will be computed. * * PARAMETER3: float - Address of the statistical average * PARAMETER4: float - Address of the point statistical geometric mean * PARAMETER5: int - Maximum element value in the array * PARAMETER6: int - Minimum element value in the array * DESCRIPTION: Computes the statistical parameters for the data array. * RETURN VALUE: None. * NOTES: None * END DESCRIPTION ****************************************************/ g. Function instantiation i. Comments for individual lines of code are on an as needed basis ii. All opening and closing braces must be on their own line and in the same columns
Page6 iii. All statements following an opening brace must be indented one tab space as per this example: void statistics(int n, int *array, float *xavg, float *xmean, int *xmax, int *xmin) { function_run_counter(); // Count function executed 1 *xavg = arithmetric_mean(n, array); function_run_counter(); // Count function executed 2 *xmean = geometric_mean(n, array); function_run_counter(); // Count function executed 3 *xmin = minimum(n, array); function_run_counter(); // Count function executed 4 *xmax = maximum(n, array); function_run_counter(); // Count function executed 5 } /* End of statistics */ h. Function termination: The program line containing the last brace in a function will contain the comment: /* End of Function_Name */ i. Program termination: The last line of a program file will contain the line: /* End of File_Name.c */ j. Comments: i. Block Comments: /***************************************************************** * text * text * text *****************************************************************/ ii. Line comments: 1. // text 2. /* text */