Вы находитесь на странице: 1из 7

Internal Template Version: 04

Guidelines for C Effective Date: 28th Dec, 2001

Guidelines for C
Following are the coding standards for C programming language. C coding standards will be
described under the following sections:
• Variables and Data
• Operators
• Functions
• General guidelines

Variables and Data:

Rules for Variables:


• All variable names should be written using a combination of upper case and lower-case
letters.
• First letter of the variable name must be in lower-case, and first letter of each new word
must be in upper case.
e.g. txnCount txnStatusTable
• All names should be declared explicitly and their sequence of declarations should be as
following:
o External names,
o Other names.
• There should be only one declaration per source line, and a comment must be given to
explain the use.
• All the global variables must be initialized before use, preferably at the time of
declaration.
e.g.
o char newChar_l /* For reading a character. */
o float initBal_g = INITBAL; /* Initial balance */
• Initializers of structures, unions, and arrays should be formatted with one row per line. If
row size is greater than the line width, then continue the row on the next line with the
indent of the first element of the row.
e.g.
o static short inputs_g[XMAX][YMAX] =
o {
{ 1, 2, 3, 4, 5 }
{ 6, 7, 8, 9,10 }
};
o int matrix1_g[XLEN][YLEN]
o { { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,110, 120 }
{ 23, 32, 6, 435, 44, 42, 75, 43, 34, 55,43, 45 }
};

Choosing Names:
• Meaningful names for variables, constants and functions should be chosen.

• They should be exact and consistent throughout the program.

• Abbreviations for the names should be chosen with uniform scheme.

• All the abbreviations used for a project should be stored in a file, which is accessible to all
team members.

• Names should not be redefined in inner blocks.

CMC Limited For Internal Use Only Page: 1 of 7


CMM Date: 15th Feb, 2003 Version No: 01
Internal Template Version: 04
Guidelines for C Effective Date: 28th Dec, 2001

• Variables of all classes should be suffixed with an underscore, followed by one, two or
three character; signifying its class as given below:
Major suffixes
o Global variables: '_g'
o Local variables: '_l'
o File variables: '_f'
e.g.
long lowerLimit_g; /* Minimum value */
long upperLimit_g; /* Maximum value */
char count_l; /* Count of input value */
short noOfPages_l = 0; /* Number of pages */

• Formal parameters must be suffixed as following:


o Input parameters to be suffixed with: '_i'
o Output parameters to be suffixed with: '_o'

• Input and out parameters to be suffixed with: '_io'

• In addition to the major suffix following suffix is to be used after the major suffixes.
o Pointer variables: 'p'
o Register: 'r'
o Static: 's'
e.g. node_t *nextNode_lp = NULL; /* Pointer to next node. */

• For software packages, which give a function call interface to the user, all the global
variables and functions used within the package must be protected from user programs.

• For example, you can decide to precede each such variable by E_ and function by F_.
And this should be specifically mentioned in the user manual.

Standard Defined Types:


Since implementation of C types is dependent on hardware of machine. Clarity regarding the
types is important in a project. A standard set of data types must be used to make software
portable. These defined types are mapped to raw C types of the compiler on the target machine.
This mapping table is shown below:

Mapping:

Standard Raw types Usages


defined Types
char char Text characters
SINT1 char Signed and unsigned
numbers
UINT1 unsigned char numbers
SINT2 short/int signed and unsigned
UINT2 unsigned short/int numbers
whichever has a
length of 2 bytes

CMC Limited For Internal Use Only Page: 2 of 7


CMM Date: 15th Feb, 2003 Version No: 01
Internal Template Version: 04
Guidelines for C Effective Date: 28th Dec, 2001

Standard Raw types Usages


defined Types
SINT4 long/int signed and unsigned
UINT4 unsigned long/int number which has a
length of 4 bytes
REAL4 float Signed real numbers
REAL8 double Signed real numbers
(double precision)
boolean char Boolean Values (0 or 1)

User Defined Types:


Use suffix "_t" for all names of defined types and write in lower case letters.
e.g.
typedef char name_t[NAMESIZE]; /* Name type */
/* Node type for constructing a linked list */
typedef struct
{
struct node_t *next;
SINT4 nodeVal;
} node_t;

Choosing and Using Constants:


• No constants should be hard coded within any program. Constants across files must be
shared through include files. A comment must be given for each #define statement.
• Upper case names should be used. Underscore should be used to delimit words for
enhanced readability.
e.g.
#define LINE_LENGTH 70 /* Line length */
#define MAX_NO_OF_SECTS 15 /* Max num ofsectors */ When defining constants for
character array bounds use the number of elements rather than the index of the last
element.
e.g.
#define BUFF_SIZE 63
...
char buff_l[BUFF_SIZE + 1];
• If a floating-point constant is to be defined, mention decimal point explicitly in it even
though it has an integral value.
e.g.
#define FACTOR 12.0 /* Multiplication factor. */

Type Casting:
• Do not assume default conversions of C raw types. Explicit mention of casting is needed.

Order of Evaluation of Expressions:


• Programs should not be dependent on the order of evaluation of an expression, except
as guaranteed by C for the following:
for (...; ...; expr1, expr2)
expr1 ? expr2 : expr3
expr1 && expr2
expr1 || expr2
• In all these cases, the first expression, expr1, is evaluated first.
CMC Limited For Internal Use Only Page: 3 of 7
CMM Date: 15th Feb, 2003 Version No: 01
Internal Template Version: 04
Guidelines for C Effective Date: 28th Dec, 2001

o If specific order is required, temporary variables should be used for evaluation of


sub-expressions.
o No evaluation order should be assumed in arguments of a function.
e.g.
printf("%d, %d\n", ++i_l, a[i]); /* Bad coding */

Operators:
Primary operators "->", "." and "[ ]" should be written with no space around them.
e.g.
houseRec_g->room = i_l;
studentInfo_l.grade . . .
subject_g[j_l] . . .
No space should be left between function name and its opening parenthesis and also between
opening parenthesis and first parameter; last parameter and closing parenthesis.
e.g.
convertVal(inval_i, outval_o);
There should not be any space between a unary operator and its operand.
e.g.
!finished_g
NoOfPoints_i
*house_lp
&inVal_g
sizeof(integer4)
++index
Commas should have one space after them.
e.g.
getParameters(filNam_g, noOfPrmts_l, prmtArr_g);
Other operators should have one space on either side of them.
e.g.
initval_g + displacement_l
number_l / MAX_NO_OF_VALUES

Functions:
Define a constant 'FUNCTION' as shown below.
#define FUNCTION
Write this constant before declaration of function.
e.g.
FUNCTION SINT4 convert(...)
FUNCTION void getNames(...)
Immediately after declaration of a function, give the following information about it as a comment.
• Purpose
• Input arguments
• Output arguments
• Return values
• Implicit input variables
• Implicit output variables
• Implicit i/o variables
• Calling functions (optional)
• Called functions
• Author
• Date written
• Log of changes (must contain date of making the change, Name of the person who is
making the change, and the reason for making the change)
• A comment for each local variable must be given.
• The type of value returned by a function must be specified along with declaration.
CMC Limited For Internal Use Only Page: 4 of 7
CMM Date: 15th Feb, 2003 Version No: 01
Internal Template Version: 04
Guidelines for C Effective Date: 28th Dec, 2001

• Functions external to a file must be declared explicitly using extern statement.


• As far as possible there should be only one exit path for each function.

General:

Indentation:
• Each line, which is a part of the body of a C control structure, should be indented one tab
stop (preferably two spaces) from the margin of its controlling line. The same rule applies
to structure/union definitions.
• Each opening and closing braces should be on a separate line and indented one tab stop
from the controlling keyword of C. Code inside the braces should be indented to the
same extent from them.
e.g.
if (a_l == 1)
x = y;
else
{
printf(" ... " , ...);
...
}
switch(c_g)
{
case a_g : ...
case b_g : ...
...
}

• A null statement appearing as the body of a loop must be placed in a separate line.
e.g.
nameLen = 0;
while (nameStr[nameLen++]) ; /* Null statement */
• Function definition should begin at column 1 of the line. All the parameter declarations,
and first level braces should also start at column 1. Body of the function should follow
indentation rules given above.
e.g.
FUNCTION SINT4 example(param1, param2, ...)
SINT4 param1;
UINT2 param2;
{
statement 1;
statement 2;
...
...
}

Modularity:
• Programs must be functionally divided into modules. All the operations on a data
structure must be preferably coded in the same physical file.
e.g.
The following functions operate on a data structure bitmap
set_bit()
clear_bit()
test_bit()
find_first_bit()
• All these functions can form a module and can be put in a file.

CMC Limited For Internal Use Only Page: 5 of 7


CMM Date: 15th Feb, 2003 Version No: 01
Internal Template Version: 04
Guidelines for C Effective Date: 28th Dec, 2001

• In a file with multiple functions, it is recommended that a natural top-down order be


adopted in physical sequencing of functions. It is expected that a referred function will be
found further down the physical file.

Include files:
• If the software for a project consists of large number of program files, the information
required by more than one program must be stored in a file and should be shared by all
the programs needing the information by including the file.
• There may be more than one such file. The point to be considered is that a program
should not have information visible to it, which is not used by the program.

Some examples of such files are:


• File of Global Variables
• File of Symbolic Constants
• File of User Defined Types

Environmental Features:
• Segregate environment specific code into specific small functions. It helps in
minimizing and eases the work in porting software to a new environment.
e.g.
strcpy(drive_g, "/user/catalog"); /* Bad */
getDriveName(drive_g); /* Good - dependence is */
/* in small function. */

Writing Macros:
• Macros should be given upper-case names.
e.g.
MAX(x, y) /* Gives maximum of x and y */
ABS(x) /* Gives absolute value of x */
• Put parenthesis around each of the parameters in the replacement text and around the
entire replacement text.
e.g.
# define SQUARE(x) ((x) * (x)) /* Square of x */

Use of Comments:
• Each program file must include a brief description of its contents in the beginning. In
addition it must have a list of all the functions defined in this file along with the formal
parameters. The list must maintain the order in which functions physically appear in the
file.
• All the control structures involving evaluation of various conditions, branching or looping
must be very clearly documented to give a clear picture of the processing taking place.
For example all if-then-else, while, do-while, goto, switch etc. must be documented in
the program file along the code.
• Every logical group of statements should be commented before the start of the
statements. This comment should be preceded by at least one blank line.
• If a statement needs clarification, comment should be placed one tab space away from
the statement.
• Functions must be clearly demarcated from each other by a line consisting of

/************* Name of the function *************/


over the full length of the line.

Closing of Files:
CMC Limited For Internal Use Only Page: 6 of 7
CMM Date: 15th Feb, 2003 Version No: 01
Internal Template Version: 04
Guidelines for C Effective Date: 28th Dec, 2001

• Explicitly close all the files opened by a program when the usage is over.

Diagnostic Messages:
• In order to help in subsequent debugging you must include printf statements for various
important variables at strategic places in all your programs. However these statements
must be enclosed within
#ifdef DEBUG
#endif
construct.
• These printf statements can be further divided into various levels depending on details
of information printed. The selection of a level can be controlled by use of a runtime
global variable for the entire program.
• The details could include diagnostic messages to trace the execution sequence of
various functions, printing of important parameters at entry to a function etc. You must
have the following for every function:
o A message indicating entry to the function
o A message indicating return from the function must be included in all return
paths.

Error messages:
• Error messages given by various programs should not be hardcoded.
All the messages should be stored in a file and must be accessed by using an error
number. For example an error message when printed can have the following format:

o S-M-F-N-Error message

S : Severity code (Information, Warning or Fatal)


M : Module name generating the error
F : Function name generating the error
N : Error number
For messages, and numbers decide upon a uniform style to be followed by the
entire development team for a project.
For example:
101 F Error message 1 of group 1
102 W Error message 2 of group 1
103 F Error message 3 of group 1
201 I Error message 1 of group 2
202 F Error message 2 of group 2
203 W Error message 3 of group 2
301 W Error message 1 of group 3
302 W Error message 2 of group 3
303 F Error message 3 of group 3
• Error messages should be divided into different groups depending on
functionality of the system. You may leave some gap between error numbers of different
groups for adding more messages in future.

CMC Limited For Internal Use Only Page: 7 of 7


CMM Date: 15th Feb, 2003 Version No: 01

Вам также может понравиться