SlideShare a Scribd company logo
C/C++ Coding Guidlines
Author(s): Tom Goodale
Document Filename: C/C++ Coding Guidlines
Work package: Technical Board
Partner(s): ALL
Lead Partner: AEI
Conļ¬g ID:
Document classiļ¬cation: Internal, Informational
Abstract: This Documents presents the C and C++ coding conventions as used by the
GridLab project. It is accompanied by similar documents for Java and Perl, and
by guidlines for Makeļ¬les, conļ¬gure scripts and LATEX documents. They should
be followed by all partners and are subject for reviews by the Quality Assurance
manager of the project.
2002/05/02 ā€“ 22:26:22
C/C++ Coding Guidlines
Contents
1 C and C++ 2
1.1 File Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.1 Line Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.2 Wrapping Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6.1 Implementation Comment Formats . . . . . . . . . . . . . . . . . . . . . . 6
1.6.2 Documentation Comments . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.1 Number Per Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.2 Initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.3 Placement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.4 Function Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.8 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8.1 Simple Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8.2 Compound Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8.3 return Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8.4 if, if-else, if else-if else Statements . . . . . . . . . . . . . . . . . . . . . . . 10
1.8.5 for Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8.6 while Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8.7 do-while Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8.8 switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9 White Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9.1 Blank Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9.2 Blank Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.10 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.11 Programming Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.11.1 Adherence to Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.11.2 Use typedef in preference to #deļ¬nes . . . . . . . . . . . . . . . . . . . . 14
1.11.3 Use of const qualiļ¬er . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.11.4 Global and Static variables . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.11.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.11.6 Variable Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.11.7 Miscellaneous Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2002/05/02 ā€“ 22:26:22
Internal, Informational 1/17
C/C++ Coding Guidlines
1 C and C++
These coding conventions are adapted with permission from the Cactus Coding conventions. See
http://www.cactuscode.org/. These have been formatted in the same way as the Java coding
guidelines for consistency and some of those conventions adopted where there was no conļ¬‚ict.
1.1 File Organization
A ļ¬le consists of sections that should be separated by blank lines and an optional comment
identifying each section.
1.2 File Names
File names should be all lowercase, with the extension .h for include ļ¬les, .c for C source ļ¬les,
and .cpp for C++ source ļ¬les. The ļ¬le names should reļ¬‚ect the functionality deļ¬ned/implemented
in that ļ¬le. Files with logical connection (e.g. pairs of header and source ļ¬les) should reļ¬‚ect that
connection in their names wherever possible. Files belonging to the same moduleshould reļ¬‚ect
that dependency by a short uniq preļ¬x to the ļ¬lename, followed by an underscore. Followin
example illustrate these convention:
GNUmakefile io_base.cpp
server.c io_base.h
server_ioplug.h io_file.h
server_ioplug.c io_file.cpp
io_cwrapper.h io_stream.h
io_cwrapper.c io_stream.cpp
1.3 Source Files
C and C++ source ļ¬les have the following ordering:
ā€¢ Beginning comments (see ā€œBeginning Commentsā€ on 3)
ā€¢ cvs version information
ā€¢ #include statements
ā€¢ #deļ¬nes.
ā€¢ local data type deļ¬nitions.
ā€¢ local (static) function prototypes.
ā€¢ local (static) data.
ā€¢ externally visible functions.
ā€¢ local (static) functions.
2002/05/02 ā€“ 22:26:22
Internal, Informational 2/17
C/C++ Coding Guidlines
Beginning Comments All source ļ¬les should begin with a comment that describes the ļ¬le
and its contents along with the date of creation, CVS version information, and a copyright
statement.
/** @file <filename>
* Brief description of contents of file.
*
* Long description
*
* @date <date of creation of file>
*
* @version <CVS $ Header $ field>
* Copyright notice.
*/
Note: This is a documentation comment ā€“ see section 1.6.2 for details.
CVS Version Information After the documentation header, there should be a single line
static const char *rcsid = ā€$Header$ā€;
containing the CVS version information as a static. This can be subsequently extracted from
the object ļ¬le if there is doubt as to the version of the source code which was compiled.
1.4 Header Files
All header ļ¬les should begin with a comment that describes the ļ¬le and its contents along with
the date of creation, CVS version information, and a copyright statement.
/** @file <filename>
* Brief description of contents of file.
*
* Long description
*
* @date <date of creation of file>
*
* @version <CVS $ Header $ field>
* Copyright notice.
*/
Note: This is a documentation comment ā€“ see section 1.6.2 for details.
To protect against multiple inclusion of headers, the contents of a header ļ¬le should be protected
by a #ifndef ... #endif pair.
#ifndef _NAMEOFHEADERFILEINCAPITALS_H_
#define _NAMEOFHEADERFILEINCAPITALS_H_ 1
...body of header file...
2002/05/02 ā€“ 22:26:22
Internal, Informational 3/17
C/C++ Coding Guidlines
#endif /* _NAMEOFHEADERFILEINCAPITALS_H_ */
Function prototypes in C header ļ¬les should be protected against C++ linkage by
#ifdef __cplusplus
extern "C"
{
#endif
...prototypes...
#ifdef __cplusplus
}
#endif
As a general rule header ļ¬les should not include system header ļ¬les, but should rather document
which system header ļ¬les they require.
1.5 Indentation
Two spaces should be used as the unit of indentation. Tabs should not be used as inconsistent
use of tabs and spaces leads to diļ¬ƒculties when using ā€œdiļ¬€ā€ or other tools to compare ļ¬les.
1.5.1 Line Length
Avoid lines longer than 80 characters, since theyā€™re not handled well by many terminals and
tools.
Note:
Examples for use in documentation should have a shorter line length-generally no more than 70
characters.
1.5.2 Wrapping Lines
When an expression will not ļ¬t on a single line, break it according to these general principles:
ā€¢ Break after a comma.
ā€¢ Break before an operator.
ā€¢ Prefer higher-level breaks to lower-level breaks.
ā€¢ Align the new line with the beginning of the expression at the same level on the previous
line.
ā€¢ If the above rules lead to confusing code or to code thatā€™s squished up against the right
margin, just indent 8 spaces instead.
Here are some examples of breaking function calls:
2002/05/02 ā€“ 22:26:22
Internal, Informational 4/17
C/C++ Coding Guidlines
Function(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);
var = Function(longExpression1,
Function2(longExpression2,
longExpression3));
Following are two examples of breaking an arithmetic expression. The ļ¬rst is preferred, since
the break occurs outside the parenthesised expression, which is at a higher level.
LongName1 = LongName2 * (LongName3 + LongName4 - LongName5)
+ 4 * longname6; /* PREFER */
LongName1 = LongName2 * (LongName3 + LongName4
- LongName5) + 4 * Longname6; /* AVOID */
Following are two examples of indenting function declarations. The ļ¬rst is the conventional
case. The second would shift the second and third lines to the far right if it used conventional
indentation, so instead it indents only 8 spaces.
/* CONVENTIONAL INDENTATION */
Function(int AnArg, double AnotherArg, char *YetAnotherArg,
int *AndStillAnother)
{
...
}
/*INDENT 8 SPACES TO AVOID VERY DEEP INDENTS */
static ReallyLongFunctionName(int AnArg,
double anotherArg, char *YetAnotherArg,
int *AndStillAnother)
{
...
}
/* OR, PUT EACH ARG ON OWN LINE */
static ReallyLongFunctionName(int AnArg,
double anotherArg,
char *YetAnotherArg,
int *AndStillAnother)
{
...
}
Here are three acceptable ways to format ternary expressions:
alpha = (aLongBooleanExpression) ? beta : gamma;
alpha = (aLongBooleanExpression) ? beta
: gamma;
2002/05/02 ā€“ 22:26:22
Internal, Informational 5/17
C/C++ Coding Guidlines
alpha = (aLongBooleanExpression)
? beta
: gamma;
1.6 Comments
Programs can have two kinds of comments: implementation comments and documentation com-
ments. Implementation comments are those found in C, which are delimited by /*...*/. Docu-
mentation comments are delimited by /**...*/. Doc comments can be extracted to HTML ļ¬les
using the doxygen tool.
Implementation comments are mean for commenting out code or for comments about the par-
ticular implementation. Doc comments are meant to describe the speciļ¬cation of the code, from
an implementation-free perspective, to be read by developers who might not necessarily have
the source code at hand.
Comments should be used to give overviews of code and provide additional information that
is not readily available in the code itself. Comments should contain only information that
is relevant to reading and understanding the program. For example, information about how
a corresponding package is built or in what directory it resides should not be included as a
comment.
Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating
information that is present in (and clear from) the code. It is too easy for redundant comments
to get out of date. In general, avoid any comments that are likely to get out of date as the code
evolves.
Note:
The frequency of comments sometimes reļ¬‚ects poor quality of code. When you feel compelled
to add a comment, consider rewriting the code to make it clearer.
Comments should not be enclosed in large boxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed and backspace.
1.6.1 Implementation Comment Formats
Programs can have four styles of implementation comments: block, single-line, trailing, and
end-of-line.
Block Comments Block comments are used to provide descriptions of ļ¬les, methods, data
structures and algorithms. Block comments may be used at the beginning of each ļ¬le and before
each method. They can also be used in other places, such as within functions. Block comments
inside a function should be indented to the same level as the code they describe.
A block comment should be preceded by a blank line to set it apart from the rest of the code.
/*
* Here is a block comment.
*/
See also ā€œDocumentation Commentsā€ on page 7.
2002/05/02 ā€“ 22:26:22
Internal, Informational 6/17
C/C++ Coding Guidlines
Single-Line Comments Short comments can appear on a single line indented to the level of
the code that follows. If a comment canā€™t be written in a single line, it should follow the block
comment format (see section 1.6.1). A single-line comment should be preceded by a blank line.
Hereā€™s an example of a single-line comment in C code (also see ā€œDocumentation Commentsā€ on
page 7):
if (condition)
{
/* Handle the condition. */
...
}
Trailing Comments Very short comments can appear on the same line as the code they
describe, but should be shifted far enough to separate them from the statements. If more than
one short comment appears in a chunk of code, they should all be indented to the same tab
setting.
Hereā€™s an example of a trailing comment in C code:
if (a == 2)
{
a = TRUE; /* special case */
}
else
{
a = isPrime(a); /* works only for odd a */
}
1.6.2 Documentation Comments
For further details, see ā€œThe Doxygen Manualā€ which includes information on the doc comment
tags (@return, @param, @see):
http://www.doxygen.org
Doxygen comments describe C functions, structures, enums, unions, etc. Each doc comment is
set inside the comment delimiters /**...*/, with one comment per class, interface, or member.
This comment should appear just before the declaration:
/**
* The Example function provides ...
*/
static Example(void)
{ ...
The ļ¬rst line of doc comment (/**) is not indented relative to the surrounding block; subsequent
doc comment lines each have 1 space of indentation (to vertically align the asterisks).
If you need to give information that isnā€™t appropriate for documentation, use an implementation
block comment (see section 1.6.1) or single-line (see section 1.6.1) comment immediately before
the declaration. For example, details about the implementation of a function should go in in
such an implementation block comment following the doc comment for the function, not in the
function doc comment.
2002/05/02 ā€“ 22:26:22
Internal, Informational 7/17
C/C++ Coding Guidlines
1.7 Declarations
1.7.1 Number Per Line
One declaration per line is recommended since it encourages commenting. In other words,
int level; /* indentation level */
int size; /* size of table */
is preferred over
int level, size;
Do not put diļ¬€erent types on the same line. Example:
int foo, fooarray[SIZE]; /* WRONG! */
Note:
The examples above use one space between the type and the identiļ¬er. Another acceptable
alternative is to line up a group of declarations (with spaces, not tabs), e.g.:
int level; /* indentation level */
int size; /* size of table */
Object currentEntry; /* currently selected table entry */
1.7.2 Initialisation
Initialisation of a variable should be done in a seperate statement to its declaration, but as soon
after the declaration as possible. The only reason not to initialise a variable straght after it is
declared is if the initial value depends on some computation occurring ļ¬rst.
1.7.3 Placement
Put declarations only at the beginning of blocks. (A block is any code surrounded by curly
braces ā€œ{ā€œ and ā€œ}ā€.) Donā€™t wait to declare variables until their ļ¬rst use; it can confuse the
unwary programmer and hamper code portability within the scope.
void MyFunction(...)
{
int int1;
int1 = 0; /* beginning of block */
if (condition)
{
int int2;
int2 = 0; /* beginning of "if" block */
...
}
}
2002/05/02 ā€“ 22:26:22
Internal, Informational 8/17
C/C++ Coding Guidlines
The one exception to the rule is indices of for loops in C++, which can be declared in the for
statement:
for (int i = 0; i < MaxLoops; i++)
{
...
}
Avoid local declarations that hide declarations at higher levels. For example, do not declare the
same variable name in an inner block:
int count;
...
int MyFunction(...)
{
if (condition)
{
int count; /* AVOID! */
...
}
...
}
1.7.4 Function Declarations
When coding C functions the following formatting rules should be followed:
ā€¢ All functions should be preceded by a documentation comment describing the function,
its arguments and return code(s).
ā€¢ Open brace ā€œ{ā€œ appears at the beginning of the line following the declaration statement
ā€¢ Closing brace ā€œ}ā€ starts a line by itself.
/** The sample function.
* This function calculates the sample thingy.
* Some more description.
*
* @param i The first argument.
* @param j the second argument.
*
* @return The sample value.
*/
int Sample(int i, int j)
{
return i+j;
}
2002/05/02 ā€“ 22:26:22
Internal, Informational 9/17
C/C++ Coding Guidlines
1.8 Statements
1.8.1 Simple Statements
Each line should contain at most one statement. Example:
argv++; /* Correct */
argc--; /* Correct */
argv++; argc--; /* AVOID! */
1.8.2 Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces ā€œ{
statements }ā€œ. See the following sections for examples.
ā€¢ The enclosed statements should be indented one more level than the compound statement.
ā€¢ The opening brace should be on a line by itself following the line that begins the compound
statement, indented to the same level as that line; the closing brace should begin a line
and be indented to the beginning of the compound statement.
ā€¢ Braces are used around all statements, even single statements, when they are part of a
control structure, such as a if-else or for statement. This makes it easier to add statements
without accidentally introducing bugs due to forgetting to add braces.
1.8.3 return Statements
A return statement with a value should not use parentheses unless they make the return value
more obvious in some way. Example:
return;
return MyDisk_size();
return (size ? size : defaultSize);
1.8.4 if, if-else, if else-if else Statements
The if-else class of statements should have the following form:
if (condition)
{
statements;
}
if (condition)
{
statements;
}
2002/05/02 ā€“ 22:26:22
Internal, Informational 10/17
C/C++ Coding Guidlines
else
{
statements;
}
if (condition)
{
statements;
}
else if (condition)
{
statements;
}
else
{
statements;
}
Note:
if statements always use braces {}. Avoid the following error-prone form:
if (condition) /*AVOID! THIS OMITS THE BRACES {}! */
statement;
1.8.5 for Statements
A for statement should have the following form:
for (initialization; condition; update)
{
statements;
}
An empty for statement (one in which all the work is done in the initialization, condition, and
update clauses) should have the following form:
for (initialization; condition; update);
When using the comma operator in the initialization or update clause of a for statement, avoid
the complexity of using more than three variables. If needed, use separate statements before the
for loop (for the initialization clause) or at the end of the loop (for the update clause).
1.8.6 while Statements
A while statement should have the following form:
while (condition)
{
statements;
}
2002/05/02 ā€“ 22:26:22
Internal, Informational 11/17
C/C++ Coding Guidlines
An empty while statement should have the following form:
while (condition);
1.8.7 do-while Statements
A do-while statement should have the following form:
do
{
statements;
} while (condition);
1.8.8 switch Statements
A switch statement should have the following form:
switch (condition)
{
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
Every time a case falls through (doesnā€™t include a break statement), add a comment where the
break statement would normally be. This is shown in the preceding code example with the /*
falls through */ comment.
Every switch statement should include a default case. The break in the default case is redundant,
but it prevents a fall-through error if later the default is changed to a speciļ¬c case and a new
default is introduced.
1.9 White Space
1.9.1 Blank Lines
Blank lines improve readability by setting oļ¬€ sections of code that are logically related.
Two blank lines should always be used in the following circumstances:
ā€¢ Between sections of a source ļ¬le
One blank line should always be used in the following circumstances:
ā€¢ Between functions
2002/05/02 ā€“ 22:26:22
Internal, Informational 12/17
C/C++ Coding Guidlines
ā€¢ Between the local variable declarations in a block and its ļ¬rst statement
ā€¢ Before a block (see section 1.6.1) or single-line (see section 1.6.1) comment
ā€¢ Between logical sections inside a function to improve readability
1.9.2 Blank Spaces
Blank spaces should be used in the following circumstances:
ā€¢ A blank space should appear after commas in argument lists.
ā€¢ All binary operators should be separated from their operands by spaces. Blank spaces
should never separate unary operators such as unary minus, increment (ā€œ++ā€), and decre-
ment (ā€œā€“ā€) from their operands. Example:
a += c + d;
a = (a + b) / (c * d);
while (d++ = s++)
{
n++;
}
ā€¢ The expressions in a for statement should be separated by blank spaces. Example:
for (expr1; expr2; expr3)
ā€¢ Casts should be followed by a blank space. Examples:
MyFunction1((char) aNum, (double) x);
MyFunction2((int) (cp + 5), ((int) (i + 3) + 1);
1.10 Naming Conventions
Naming conventions make programs more understandable by making them easier to read.
2002/05/02 ā€“ 22:26:22
Internal, Informational 13/17
C/C++ Coding Guidlines
Externally visible functions should have a short preļ¬x uniquely iden-
tifying the module, followed by an under-
score, followed by the rest of the identi-
ļ¬er which should consist of words, each of
which begins with a capital letter, with no
underscores. E.g. GAT FindResource.
Static functions should follow the same convention as ex-
ternally visible functions, but need not
have the preļ¬x.
Variable names should be short yet meaningful. The
choice of a variable name should be
mnemonic- that is, designed to indicate
to the casual observer the intent of its
use. One-character variable names should
be avoided except for temporary ā€œthrow-
awayā€ variables. Common names for tem-
porary variables are i, j, k, m, and n for
integers; c, d, and e for characters.
#deļ¬nes should be all uppercase.
typedefs and structures should have a short preļ¬x, followed by un-
derscore, followed by the rest of the iden-
tiļ¬er which should consist of words, each
of which begins with a capital letter, with
no underscores. E.g. GAT PropList.
1.11 Programming Practices
1.11.1 Adherence to Standards
All code should adhere to the ISO C or C++ standards. The presence or absence of library
functions not speciļ¬ed by the Posix standard on a particular platform should be detected by
use of Autoconf and appropriate logic emplaced to either work around the absence or provide a
good error message.
1.11.2 Use typedef in preference to #deļ¬nes
New types should be introduced via typedefs rather than by #deļ¬nes ā€“ these types are then
visible in debuggers and the compiler can do stronger type-checking.
1.11.3 Use of const qualiļ¬er
Where possible pointers should be passed using the const qualiļ¬er. This is especially important
for strings.
1.11.4 Global and Static variables
Donā€™t make any variable global or static without good reason. Access to module level statics in
other ļ¬les can often be granted via a function call rather than by making the variable global.
2002/05/02 ā€“ 22:26:22
Internal, Informational 14/17
C/C++ Coding Guidlines
1.11.5 Constants
Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, or other
numbers in loop counters.
1.11.6 Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read.
Example:
fchar = lchar = ā€™cā€™; /* AVOID! */
Do not use the assignment operator in a place where it can be easily confused with the equality
operator. Example:
if (file = fopen(...))
{ /* AVOID! */
...
}
should be written as
if ((file = fopen(...)) != NULL)
{
...
}
Do not use embedded assignments in an attempt to improve run-time performance. This is the
job of the compiler. Example:
d = (a = b + c) + r; /* AVOID! */
should be written as
a = b + c;
d = a + r;
1.11.7 Miscellaneous Practices
Parentheses It is generally a good idea to use parentheses liberally in expressions involving
mixed operators to avoid operator precedence problems. Even if the operator precedence seems
clear to you, it might not be to others-you shouldnā€™t assume that other programmers know
precedence as well as you do.
if (a == b && c == d) /* AVOID! */
if ((a == b) && (c == d)) /* RIGHT */
2002/05/02 ā€“ 22:26:22
Internal, Informational 15/17
C/C++ Coding Guidlines
Returning Values Try to make the structure of your program match the intent. Example:
if (booleanExpression)
{
return true;
}
else
{
return false;
}
should instead be written as
return booleanExpression;
Similarly,
if (condition)
{
return x;
}
return y;
should be written as
return (condition ? x : y);
There should only be one return statement in a function. Multiple returns can lead to confusion
when reading the code and is a freqent source of errors.
if(foo)
{
return a;
}
...
lots of code
...
return b;
should be written as
2002/05/02 ā€“ 22:26:22
Internal, Informational 16/17
C/C++ Coding Guidlines
if(foo)
{
retval = a;
}
else
{
...
lots of code
...
retval = b;
}
return retval;
Expressions before ā€˜?ā€™ in the Conditional Operator If an expression containing a binary
operator appears before the ? in the ternary ?: operator, it should be parenthesised. Example:
(x >= 0) ? x : -x;
Special Comments Use XXX in a comment to ļ¬‚ag something that is bogus but works. Use
FIXME to ļ¬‚ag something that is bogus and broken.
Compilation with warnings enabled It is recommended that developers compile with all
warnings enabled. Compiler warnings often ļ¬‚ag dubious practices and common coding errors.
2002/05/02 ā€“ 22:26:22
Internal, Informational 17/17

More Related Content

Viewers also liked

Q3 ā€“ production companies and distribution
Q3 ā€“ production companies and distributionQ3 ā€“ production companies and distribution
Q3 ā€“ production companies and distribution
JDCArmory
Ā 
Las app
Las appLas app
SK TUNJANGAN PROFESI TAHUN 2016
SK TUNJANGAN PROFESI TAHUN 2016SK TUNJANGAN PROFESI TAHUN 2016
SK TUNJANGAN PROFESI TAHUN 2016
vie akbar
Ā 
Modul 1 kb1 pemeriksaan fisik sistem kardiovaskuler
Modul 1 kb1 pemeriksaan fisik sistem kardiovaskulerModul 1 kb1 pemeriksaan fisik sistem kardiovaskuler
Modul 1 kb1 pemeriksaan fisik sistem kardiovaskulerUwes Chaeruman
Ā 
Modul 1 kb3 fisioterapi dada
Modul 1 kb3 fisioterapi dadaModul 1 kb3 fisioterapi dada
Modul 1 kb3 fisioterapi dadaUwes Chaeruman
Ā 
Changing scenario of packaging in pharmaceutical industries
Changing scenario of packaging in pharmaceutical industriesChanging scenario of packaging in pharmaceutical industries
Changing scenario of packaging in pharmaceutical industries
akash mitra
Ā 
Perawatan Luka
Perawatan LukaPerawatan Luka
Perawatan Luka
pjj_kemenkes
Ā 
Menerapkan Online Learning dal am Pelatihan
Menerapkan Online Learning dal am PelatihanMenerapkan Online Learning dal am Pelatihan
Menerapkan Online Learning dal am Pelatihan
Uwes Chaeruman
Ā 
Dev com history
Dev com historyDev com history
Dev com history
Mira K Desai
Ā 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
jatin batra
Ā 
Penilaian Asas Pesakit
Penilaian Asas PesakitPenilaian Asas Pesakit
Penilaian Asas PesakitTuan Haroun
Ā 
Basic safety orientation training
Basic safety orientation trainingBasic safety orientation training
Basic safety orientation training
Tony Bertram
Ā 
New Employee Safety Orientation by Houghton
New Employee Safety Orientation by HoughtonNew Employee Safety Orientation by Houghton
New Employee Safety Orientation by Houghton
Atlantic Training, LLC.
Ā 
KINDER : analyse sƩmiotique de la marque
KINDER : analyse sƩmiotique de la marqueKINDER : analyse sƩmiotique de la marque
KINDER : analyse sƩmiotique de la marque
FEPP COMMUNICATION GROUP / SPIRIT OF STAR
Ā 

Viewers also liked (14)

Q3 ā€“ production companies and distribution
Q3 ā€“ production companies and distributionQ3 ā€“ production companies and distribution
Q3 ā€“ production companies and distribution
Ā 
Las app
Las appLas app
Las app
Ā 
SK TUNJANGAN PROFESI TAHUN 2016
SK TUNJANGAN PROFESI TAHUN 2016SK TUNJANGAN PROFESI TAHUN 2016
SK TUNJANGAN PROFESI TAHUN 2016
Ā 
Modul 1 kb1 pemeriksaan fisik sistem kardiovaskuler
Modul 1 kb1 pemeriksaan fisik sistem kardiovaskulerModul 1 kb1 pemeriksaan fisik sistem kardiovaskuler
Modul 1 kb1 pemeriksaan fisik sistem kardiovaskuler
Ā 
Modul 1 kb3 fisioterapi dada
Modul 1 kb3 fisioterapi dadaModul 1 kb3 fisioterapi dada
Modul 1 kb3 fisioterapi dada
Ā 
Changing scenario of packaging in pharmaceutical industries
Changing scenario of packaging in pharmaceutical industriesChanging scenario of packaging in pharmaceutical industries
Changing scenario of packaging in pharmaceutical industries
Ā 
Perawatan Luka
Perawatan LukaPerawatan Luka
Perawatan Luka
Ā 
Menerapkan Online Learning dal am Pelatihan
Menerapkan Online Learning dal am PelatihanMenerapkan Online Learning dal am Pelatihan
Menerapkan Online Learning dal am Pelatihan
Ā 
Dev com history
Dev com historyDev com history
Dev com history
Ā 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
Ā 
Penilaian Asas Pesakit
Penilaian Asas PesakitPenilaian Asas Pesakit
Penilaian Asas Pesakit
Ā 
Basic safety orientation training
Basic safety orientation trainingBasic safety orientation training
Basic safety orientation training
Ā 
New Employee Safety Orientation by Houghton
New Employee Safety Orientation by HoughtonNew Employee Safety Orientation by Houghton
New Employee Safety Orientation by Houghton
Ā 
KINDER : analyse sƩmiotique de la marque
KINDER : analyse sƩmiotique de la marqueKINDER : analyse sƩmiotique de la marque
KINDER : analyse sƩmiotique de la marque
Ā 

Similar to Coding guideline

Code conventions
Code conventionsCode conventions
Code conventions
Hermano Portes
Ā 
Java code conventions
Java code conventionsJava code conventions
Java code conventionsArmando Daniel
Ā 
CodeConventions.pdf
CodeConventions.pdfCodeConventions.pdf
CodeConventions.pdf
Jeff Smith
Ā 
Codeconventions 150003
Codeconventions 150003Codeconventions 150003
Codeconventions 150003Tomasz Waszczyk
Ā 
Intro to embedded systems programming
Intro to embedded systems programming Intro to embedded systems programming
Intro to embedded systems programming
Massimo Talia
Ā 
Code Conventions
Code ConventionsCode Conventions
Code Conventionsprovadaordem
Ā 
Getting started erlang
Getting started erlangGetting started erlang
Getting started erlangKwanzoo Dev
Ā 
Javaprecisely
JavapreciselyJavaprecisely
JavapreciselyZhichao Zhu
Ā 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer TutorialsNont Banditwong
Ā 
CAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming ConventionsCAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming Conventions
Gerardo Renteria
Ā 
Red paper
Red paperRed paper
Red paperVideoguy
Ā 
programaciĆ³n en prolog
programaciĆ³n en prologprogramaciĆ³n en prolog
programaciĆ³n en prolog
Alex Pin
Ā 
Uni leicester
Uni leicesterUni leicester
Uni leicester
N/A
Ā 
C++ annotations version
C++ annotations versionC++ annotations version
C++ annotations version
PL Sharma
Ā 
[EN] PLC programs development guidelines
[EN] PLC programs development guidelines[EN] PLC programs development guidelines
[EN] PLC programs development guidelines
Itris Automation Square
Ā 
S Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+GuideS Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+Guideguestd2fe1e
Ā 
S Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+GuideS Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+Guideguestd2fe1e
Ā 

Similar to Coding guideline (20)

Code conventions
Code conventionsCode conventions
Code conventions
Ā 
Java code conventions
Java code conventionsJava code conventions
Java code conventions
Ā 
CodeConventions.pdf
CodeConventions.pdfCodeConventions.pdf
CodeConventions.pdf
Ā 
Codeconventions 150003
Codeconventions 150003Codeconventions 150003
Codeconventions 150003
Ā 
Intro to embedded systems programming
Intro to embedded systems programming Intro to embedded systems programming
Intro to embedded systems programming
Ā 
Code Conventions
Code ConventionsCode Conventions
Code Conventions
Ā 
Getting started erlang
Getting started erlangGetting started erlang
Getting started erlang
Ā 
Javaprecisely
JavapreciselyJavaprecisely
Javaprecisely
Ā 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer Tutorials
Ā 
CAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming ConventionsCAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming Conventions
Ā 
Red paper
Red paperRed paper
Red paper
Ā 
programaciĆ³n en prolog
programaciĆ³n en prologprogramaciĆ³n en prolog
programaciĆ³n en prolog
Ā 
Uni leicester
Uni leicesterUni leicester
Uni leicester
Ā 
Swi prolog-6.2.6
Swi prolog-6.2.6Swi prolog-6.2.6
Swi prolog-6.2.6
Ā 
C++ annotations version
C++ annotations versionC++ annotations version
C++ annotations version
Ā 
[EN] PLC programs development guidelines
[EN] PLC programs development guidelines[EN] PLC programs development guidelines
[EN] PLC programs development guidelines
Ā 
Thesis
ThesisThesis
Thesis
Ā 
S Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+GuideS Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+Guide
Ā 
S Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+GuideS Pii Plus+C+Library+Programmer+Guide
S Pii Plus+C+Library+Programmer+Guide
Ā 
PerlIntro
PerlIntroPerlIntro
PerlIntro
Ā 

Recently uploaded

Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
Ā 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
Ā 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
Ā 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
Ā 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
Ā 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
Ā 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
Ā 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
Ā 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
Ā 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
Ā 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
Ā 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
Ā 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
Ā 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
Ā 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
Ā 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
Ā 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
Ā 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
Ā 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
Ā 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
Ā 

Recently uploaded (20)

Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Ā 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Ā 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
Ā 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
Ā 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
Ā 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
Ā 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
Ā 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Ā 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
Ā 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
Ā 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Ā 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
Ā 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
Ā 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Ā 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
Ā 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Ā 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Ā 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Ā 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Ā 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Ā 

Coding guideline

  • 1. C/C++ Coding Guidlines Author(s): Tom Goodale Document Filename: C/C++ Coding Guidlines Work package: Technical Board Partner(s): ALL Lead Partner: AEI Conļ¬g ID: Document classiļ¬cation: Internal, Informational Abstract: This Documents presents the C and C++ coding conventions as used by the GridLab project. It is accompanied by similar documents for Java and Perl, and by guidlines for Makeļ¬les, conļ¬gure scripts and LATEX documents. They should be followed by all partners and are subject for reviews by the Quality Assurance manager of the project. 2002/05/02 ā€“ 22:26:22
  • 2. C/C++ Coding Guidlines Contents 1 C and C++ 2 1.1 File Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.5 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.5.1 Line Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.5.2 Wrapping Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.6 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.6.1 Implementation Comment Formats . . . . . . . . . . . . . . . . . . . . . . 6 1.6.2 Documentation Comments . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.7 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.7.1 Number Per Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.7.2 Initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.7.3 Placement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.7.4 Function Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.8 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.8.1 Simple Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.8.2 Compound Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.8.3 return Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.8.4 if, if-else, if else-if else Statements . . . . . . . . . . . . . . . . . . . . . . . 10 1.8.5 for Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.8.6 while Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.8.7 do-while Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.8.8 switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.9 White Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.9.1 Blank Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.9.2 Blank Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.10 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.11 Programming Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.11.1 Adherence to Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.11.2 Use typedef in preference to #deļ¬nes . . . . . . . . . . . . . . . . . . . . 14 1.11.3 Use of const qualiļ¬er . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.11.4 Global and Static variables . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.11.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.11.6 Variable Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.11.7 Miscellaneous Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2002/05/02 ā€“ 22:26:22 Internal, Informational 1/17
  • 3. C/C++ Coding Guidlines 1 C and C++ These coding conventions are adapted with permission from the Cactus Coding conventions. See http://www.cactuscode.org/. These have been formatted in the same way as the Java coding guidelines for consistency and some of those conventions adopted where there was no conļ¬‚ict. 1.1 File Organization A ļ¬le consists of sections that should be separated by blank lines and an optional comment identifying each section. 1.2 File Names File names should be all lowercase, with the extension .h for include ļ¬les, .c for C source ļ¬les, and .cpp for C++ source ļ¬les. The ļ¬le names should reļ¬‚ect the functionality deļ¬ned/implemented in that ļ¬le. Files with logical connection (e.g. pairs of header and source ļ¬les) should reļ¬‚ect that connection in their names wherever possible. Files belonging to the same moduleshould reļ¬‚ect that dependency by a short uniq preļ¬x to the ļ¬lename, followed by an underscore. Followin example illustrate these convention: GNUmakefile io_base.cpp server.c io_base.h server_ioplug.h io_file.h server_ioplug.c io_file.cpp io_cwrapper.h io_stream.h io_cwrapper.c io_stream.cpp 1.3 Source Files C and C++ source ļ¬les have the following ordering: ā€¢ Beginning comments (see ā€œBeginning Commentsā€ on 3) ā€¢ cvs version information ā€¢ #include statements ā€¢ #deļ¬nes. ā€¢ local data type deļ¬nitions. ā€¢ local (static) function prototypes. ā€¢ local (static) data. ā€¢ externally visible functions. ā€¢ local (static) functions. 2002/05/02 ā€“ 22:26:22 Internal, Informational 2/17
  • 4. C/C++ Coding Guidlines Beginning Comments All source ļ¬les should begin with a comment that describes the ļ¬le and its contents along with the date of creation, CVS version information, and a copyright statement. /** @file <filename> * Brief description of contents of file. * * Long description * * @date <date of creation of file> * * @version <CVS $ Header $ field> * Copyright notice. */ Note: This is a documentation comment ā€“ see section 1.6.2 for details. CVS Version Information After the documentation header, there should be a single line static const char *rcsid = ā€$Header$ā€; containing the CVS version information as a static. This can be subsequently extracted from the object ļ¬le if there is doubt as to the version of the source code which was compiled. 1.4 Header Files All header ļ¬les should begin with a comment that describes the ļ¬le and its contents along with the date of creation, CVS version information, and a copyright statement. /** @file <filename> * Brief description of contents of file. * * Long description * * @date <date of creation of file> * * @version <CVS $ Header $ field> * Copyright notice. */ Note: This is a documentation comment ā€“ see section 1.6.2 for details. To protect against multiple inclusion of headers, the contents of a header ļ¬le should be protected by a #ifndef ... #endif pair. #ifndef _NAMEOFHEADERFILEINCAPITALS_H_ #define _NAMEOFHEADERFILEINCAPITALS_H_ 1 ...body of header file... 2002/05/02 ā€“ 22:26:22 Internal, Informational 3/17
  • 5. C/C++ Coding Guidlines #endif /* _NAMEOFHEADERFILEINCAPITALS_H_ */ Function prototypes in C header ļ¬les should be protected against C++ linkage by #ifdef __cplusplus extern "C" { #endif ...prototypes... #ifdef __cplusplus } #endif As a general rule header ļ¬les should not include system header ļ¬les, but should rather document which system header ļ¬les they require. 1.5 Indentation Two spaces should be used as the unit of indentation. Tabs should not be used as inconsistent use of tabs and spaces leads to diļ¬ƒculties when using ā€œdiļ¬€ā€ or other tools to compare ļ¬les. 1.5.1 Line Length Avoid lines longer than 80 characters, since theyā€™re not handled well by many terminals and tools. Note: Examples for use in documentation should have a shorter line length-generally no more than 70 characters. 1.5.2 Wrapping Lines When an expression will not ļ¬t on a single line, break it according to these general principles: ā€¢ Break after a comma. ā€¢ Break before an operator. ā€¢ Prefer higher-level breaks to lower-level breaks. ā€¢ Align the new line with the beginning of the expression at the same level on the previous line. ā€¢ If the above rules lead to confusing code or to code thatā€™s squished up against the right margin, just indent 8 spaces instead. Here are some examples of breaking function calls: 2002/05/02 ā€“ 22:26:22 Internal, Informational 4/17
  • 6. C/C++ Coding Guidlines Function(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = Function(longExpression1, Function2(longExpression2, longExpression3)); Following are two examples of breaking an arithmetic expression. The ļ¬rst is preferred, since the break occurs outside the parenthesised expression, which is at a higher level. LongName1 = LongName2 * (LongName3 + LongName4 - LongName5) + 4 * longname6; /* PREFER */ LongName1 = LongName2 * (LongName3 + LongName4 - LongName5) + 4 * Longname6; /* AVOID */ Following are two examples of indenting function declarations. The ļ¬rst is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces. /* CONVENTIONAL INDENTATION */ Function(int AnArg, double AnotherArg, char *YetAnotherArg, int *AndStillAnother) { ... } /*INDENT 8 SPACES TO AVOID VERY DEEP INDENTS */ static ReallyLongFunctionName(int AnArg, double anotherArg, char *YetAnotherArg, int *AndStillAnother) { ... } /* OR, PUT EACH ARG ON OWN LINE */ static ReallyLongFunctionName(int AnArg, double anotherArg, char *YetAnotherArg, int *AndStillAnother) { ... } Here are three acceptable ways to format ternary expressions: alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; 2002/05/02 ā€“ 22:26:22 Internal, Informational 5/17
  • 7. C/C++ Coding Guidlines alpha = (aLongBooleanExpression) ? beta : gamma; 1.6 Comments Programs can have two kinds of comments: implementation comments and documentation com- ments. Implementation comments are those found in C, which are delimited by /*...*/. Docu- mentation comments are delimited by /**...*/. Doc comments can be extracted to HTML ļ¬les using the doxygen tool. Implementation comments are mean for commenting out code or for comments about the par- ticular implementation. Doc comments are meant to describe the speciļ¬cation of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand. Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how a corresponding package is built or in what directory it resides should not be included as a comment. Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves. Note: The frequency of comments sometimes reļ¬‚ects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer. Comments should not be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace. 1.6.1 Implementation Comment Formats Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line. Block Comments Block comments are used to provide descriptions of ļ¬les, methods, data structures and algorithms. Block comments may be used at the beginning of each ļ¬le and before each method. They can also be used in other places, such as within functions. Block comments inside a function should be indented to the same level as the code they describe. A block comment should be preceded by a blank line to set it apart from the rest of the code. /* * Here is a block comment. */ See also ā€œDocumentation Commentsā€ on page 7. 2002/05/02 ā€“ 22:26:22 Internal, Informational 6/17
  • 8. C/C++ Coding Guidlines Single-Line Comments Short comments can appear on a single line indented to the level of the code that follows. If a comment canā€™t be written in a single line, it should follow the block comment format (see section 1.6.1). A single-line comment should be preceded by a blank line. Hereā€™s an example of a single-line comment in C code (also see ā€œDocumentation Commentsā€ on page 7): if (condition) { /* Handle the condition. */ ... } Trailing Comments Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. Hereā€™s an example of a trailing comment in C code: if (a == 2) { a = TRUE; /* special case */ } else { a = isPrime(a); /* works only for odd a */ } 1.6.2 Documentation Comments For further details, see ā€œThe Doxygen Manualā€ which includes information on the doc comment tags (@return, @param, @see): http://www.doxygen.org Doxygen comments describe C functions, structures, enums, unions, etc. Each doc comment is set inside the comment delimiters /**...*/, with one comment per class, interface, or member. This comment should appear just before the declaration: /** * The Example function provides ... */ static Example(void) { ... The ļ¬rst line of doc comment (/**) is not indented relative to the surrounding block; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). If you need to give information that isnā€™t appropriate for documentation, use an implementation block comment (see section 1.6.1) or single-line (see section 1.6.1) comment immediately before the declaration. For example, details about the implementation of a function should go in in such an implementation block comment following the doc comment for the function, not in the function doc comment. 2002/05/02 ā€“ 22:26:22 Internal, Informational 7/17
  • 9. C/C++ Coding Guidlines 1.7 Declarations 1.7.1 Number Per Line One declaration per line is recommended since it encourages commenting. In other words, int level; /* indentation level */ int size; /* size of table */ is preferred over int level, size; Do not put diļ¬€erent types on the same line. Example: int foo, fooarray[SIZE]; /* WRONG! */ Note: The examples above use one space between the type and the identiļ¬er. Another acceptable alternative is to line up a group of declarations (with spaces, not tabs), e.g.: int level; /* indentation level */ int size; /* size of table */ Object currentEntry; /* currently selected table entry */ 1.7.2 Initialisation Initialisation of a variable should be done in a seperate statement to its declaration, but as soon after the declaration as possible. The only reason not to initialise a variable straght after it is declared is if the initial value depends on some computation occurring ļ¬rst. 1.7.3 Placement Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces ā€œ{ā€œ and ā€œ}ā€.) Donā€™t wait to declare variables until their ļ¬rst use; it can confuse the unwary programmer and hamper code portability within the scope. void MyFunction(...) { int int1; int1 = 0; /* beginning of block */ if (condition) { int int2; int2 = 0; /* beginning of "if" block */ ... } } 2002/05/02 ā€“ 22:26:22 Internal, Informational 8/17
  • 10. C/C++ Coding Guidlines The one exception to the rule is indices of for loops in C++, which can be declared in the for statement: for (int i = 0; i < MaxLoops; i++) { ... } Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block: int count; ... int MyFunction(...) { if (condition) { int count; /* AVOID! */ ... } ... } 1.7.4 Function Declarations When coding C functions the following formatting rules should be followed: ā€¢ All functions should be preceded by a documentation comment describing the function, its arguments and return code(s). ā€¢ Open brace ā€œ{ā€œ appears at the beginning of the line following the declaration statement ā€¢ Closing brace ā€œ}ā€ starts a line by itself. /** The sample function. * This function calculates the sample thingy. * Some more description. * * @param i The first argument. * @param j the second argument. * * @return The sample value. */ int Sample(int i, int j) { return i+j; } 2002/05/02 ā€“ 22:26:22 Internal, Informational 9/17
  • 11. C/C++ Coding Guidlines 1.8 Statements 1.8.1 Simple Statements Each line should contain at most one statement. Example: argv++; /* Correct */ argc--; /* Correct */ argv++; argc--; /* AVOID! */ 1.8.2 Compound Statements Compound statements are statements that contain lists of statements enclosed in braces ā€œ{ statements }ā€œ. See the following sections for examples. ā€¢ The enclosed statements should be indented one more level than the compound statement. ā€¢ The opening brace should be on a line by itself following the line that begins the compound statement, indented to the same level as that line; the closing brace should begin a line and be indented to the beginning of the compound statement. ā€¢ Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces. 1.8.3 return Statements A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example: return; return MyDisk_size(); return (size ? size : defaultSize); 1.8.4 if, if-else, if else-if else Statements The if-else class of statements should have the following form: if (condition) { statements; } if (condition) { statements; } 2002/05/02 ā€“ 22:26:22 Internal, Informational 10/17
  • 12. C/C++ Coding Guidlines else { statements; } if (condition) { statements; } else if (condition) { statements; } else { statements; } Note: if statements always use braces {}. Avoid the following error-prone form: if (condition) /*AVOID! THIS OMITS THE BRACES {}! */ statement; 1.8.5 for Statements A for statement should have the following form: for (initialization; condition; update) { statements; } An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form: for (initialization; condition; update); When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause). 1.8.6 while Statements A while statement should have the following form: while (condition) { statements; } 2002/05/02 ā€“ 22:26:22 Internal, Informational 11/17
  • 13. C/C++ Coding Guidlines An empty while statement should have the following form: while (condition); 1.8.7 do-while Statements A do-while statement should have the following form: do { statements; } while (condition); 1.8.8 switch Statements A switch statement should have the following form: switch (condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case XYZ: statements; break; default: statements; break; } Every time a case falls through (doesnā€™t include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment. Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later the default is changed to a speciļ¬c case and a new default is introduced. 1.9 White Space 1.9.1 Blank Lines Blank lines improve readability by setting oļ¬€ sections of code that are logically related. Two blank lines should always be used in the following circumstances: ā€¢ Between sections of a source ļ¬le One blank line should always be used in the following circumstances: ā€¢ Between functions 2002/05/02 ā€“ 22:26:22 Internal, Informational 12/17
  • 14. C/C++ Coding Guidlines ā€¢ Between the local variable declarations in a block and its ļ¬rst statement ā€¢ Before a block (see section 1.6.1) or single-line (see section 1.6.1) comment ā€¢ Between logical sections inside a function to improve readability 1.9.2 Blank Spaces Blank spaces should be used in the following circumstances: ā€¢ A blank space should appear after commas in argument lists. ā€¢ All binary operators should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (ā€œ++ā€), and decre- ment (ā€œā€“ā€) from their operands. Example: a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } ā€¢ The expressions in a for statement should be separated by blank spaces. Example: for (expr1; expr2; expr3) ā€¢ Casts should be followed by a blank space. Examples: MyFunction1((char) aNum, (double) x); MyFunction2((int) (cp + 5), ((int) (i + 3) + 1); 1.10 Naming Conventions Naming conventions make programs more understandable by making them easier to read. 2002/05/02 ā€“ 22:26:22 Internal, Informational 13/17
  • 15. C/C++ Coding Guidlines Externally visible functions should have a short preļ¬x uniquely iden- tifying the module, followed by an under- score, followed by the rest of the identi- ļ¬er which should consist of words, each of which begins with a capital letter, with no underscores. E.g. GAT FindResource. Static functions should follow the same convention as ex- ternally visible functions, but need not have the preļ¬x. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary ā€œthrow- awayā€ variables. Common names for tem- porary variables are i, j, k, m, and n for integers; c, d, and e for characters. #deļ¬nes should be all uppercase. typedefs and structures should have a short preļ¬x, followed by un- derscore, followed by the rest of the iden- tiļ¬er which should consist of words, each of which begins with a capital letter, with no underscores. E.g. GAT PropList. 1.11 Programming Practices 1.11.1 Adherence to Standards All code should adhere to the ISO C or C++ standards. The presence or absence of library functions not speciļ¬ed by the Posix standard on a particular platform should be detected by use of Autoconf and appropriate logic emplaced to either work around the absence or provide a good error message. 1.11.2 Use typedef in preference to #deļ¬nes New types should be introduced via typedefs rather than by #deļ¬nes ā€“ these types are then visible in debuggers and the compiler can do stronger type-checking. 1.11.3 Use of const qualiļ¬er Where possible pointers should be passed using the const qualiļ¬er. This is especially important for strings. 1.11.4 Global and Static variables Donā€™t make any variable global or static without good reason. Access to module level statics in other ļ¬les can often be granted via a function call rather than by making the variable global. 2002/05/02 ā€“ 22:26:22 Internal, Informational 14/17
  • 16. C/C++ Coding Guidlines 1.11.5 Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, or other numbers in loop counters. 1.11.6 Variable Assignments Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: fchar = lchar = ā€™cā€™; /* AVOID! */ Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example: if (file = fopen(...)) { /* AVOID! */ ... } should be written as if ((file = fopen(...)) != NULL) { ... } Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example: d = (a = b + c) + r; /* AVOID! */ should be written as a = b + c; d = a + r; 1.11.7 Miscellaneous Practices Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others-you shouldnā€™t assume that other programmers know precedence as well as you do. if (a == b && c == d) /* AVOID! */ if ((a == b) && (c == d)) /* RIGHT */ 2002/05/02 ā€“ 22:26:22 Internal, Informational 15/17
  • 17. C/C++ Coding Guidlines Returning Values Try to make the structure of your program match the intent. Example: if (booleanExpression) { return true; } else { return false; } should instead be written as return booleanExpression; Similarly, if (condition) { return x; } return y; should be written as return (condition ? x : y); There should only be one return statement in a function. Multiple returns can lead to confusion when reading the code and is a freqent source of errors. if(foo) { return a; } ... lots of code ... return b; should be written as 2002/05/02 ā€“ 22:26:22 Internal, Informational 16/17
  • 18. C/C++ Coding Guidlines if(foo) { retval = a; } else { ... lots of code ... retval = b; } return retval; Expressions before ā€˜?ā€™ in the Conditional Operator If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesised. Example: (x >= 0) ? x : -x; Special Comments Use XXX in a comment to ļ¬‚ag something that is bogus but works. Use FIXME to ļ¬‚ag something that is bogus and broken. Compilation with warnings enabled It is recommended that developers compile with all warnings enabled. Compiler warnings often ļ¬‚ag dubious practices and common coding errors. 2002/05/02 ā€“ 22:26:22 Internal, Informational 17/17