79
TMA Training Center C/C++ Coding Guideline SW-GU-003 Version 1.0

C&C++Coding Guideline

Embed Size (px)

DESCRIPTION

C&C++Coding Guideline

Citation preview

C/C++ Coding Guideline

TMA Training CenterTMA Training CenterC/C++ Coding GuidelineCode: SW-GU-003

Issue Date: Apr 12, 06Version:1.0

C/C++ Coding GuidelineSW-GU-003

Version 1.0

Table of Contents

1. Introduction61.1 Purpose61.2 Scope61.3 Definitions, Acronyms and Abbreviations61.4 References62. Overview83. Comment Convention8 Rule 1: Always use documentation comment immediately before declaration.8

Rule 2: Do not use C-Style comment.9

Rule 3: Always use comment with //.10

Rule 4: Do not leave commented out software in a file.10

Rule 5: Do not include anything except description in comment.11

Rule 6: Do not put comment at the end of line.11

4. Naming Convention13 Rule 1: Always capitalize the first letter and letters as word separators of name only13

Rule 2: Do not use acronyms in names unless the acronym is defined in user document.14

Rule 3: Always use verb for first word and use verb opposites for opposite actions.14

Rule 4: Always include a prefix on global and namespace names.15

Rule 5: Always include a prefix on member name.16

Rule 6: Always include a prefix on local name.17

Rule 7: Always 1st letter is lowercase and only letters as word separators is uppercase.18

Rule 8: Do not include any underscore in name except after variables prefix.18

Rule 9: Always make all letters of name uppercase.19

Rule 10: Always make a combination of plane words by using underscore ( _ ).19

Rule 11: Do not pluralize enumerated type name.20

Rule 12: Never use number as word.20

Rule 13: Always make sure that argument names and its purposes are the same.20

Rule 14: Always name header and implement files the same as class name.21

5. Format Convention22 Rule 1: Always indent new scope with two additional spaces.22

Rule 2: Do not allow line to exceed 80 characters.23

Rule 3: Always use space instead of tab.23

Rule 4: Do not code more than one statement per line.23

Rule 5: Always add one more empty line between each section.24

Rule 6: Always make level alignment of every code section.25

Rule 7: Always put pair of braces around statement on new line even single line of code.25

6. Constant Convention27 Rule 1: Do not use #define to create the constant.27

Rule 2: Do not use #define to create method-like macros.27

Rule 3: Always declare the constant when possible.28

Rule 4: Always define constant for literal except 0, 1 and true, false.30

7. Operator Convention30 Rule 1: Do not add a white space between unary operator and its operand.31

Rule 2: Always add a white space before and after to operators.31

Rule 3: Do not use ? operator.32

8. Control Flow Convention33 Rule 1: Do not change a loop variable inside for loop block.33

Rule 2: Always add default for switch statement.33

Rule 3: Always follow the sample of statements as following form.34

Rule 4: Do not use goto keyword to replace control flow statements or other purposes.35

9. Expression Convention37 Rule 1: Always avoid embedding the assignment within another expression.37

Rule 2: Should put the constant, TRUE/FALSE, .. on the left of comparison expression.37

Rule 3: Do not use integer variable as bool variable in conditional expression.38

Rule 4: Always include parenthesis in expression if possible.39

Rule 5: Always separate operators groups from parenthesis.40

10. Pointer and Memory Management Convention40 Rule 1: Do not use malloc, free, calloc, realloc, and ... operators from standard C.40

Rule 2: Always use new and delete operators consistently and accurately.41

Rule 3: Always check existence of pointer before using it.42

Rule 4: Should use 0 instead of NULL.43

Rule 5: Should implement exception handling as needed.43

Rule 6: Should use exception handling instead of status value and error code.44

11. Variable and Data Types Convention45 Rule 1: Should use unsigned data type when value can not be negative.45

Rule 2: Do not have method and non-public variable members in a structure.45

Rule 3: Always postpone variable definition as long as possible.46

Rule 4: Do not use the same variable name in outer and inner scopes.47

Rule 5: Do not declare member variables as non-private.48

12. Method Convention48 Rule 1: Always order method arguments as follows: input, input and output, and output.49

Rule 2: Do not pass class and structure arguments by value.49

Rule 3: Always name method arguments.49

Rule 4: Always place return statement at the last line of method.50

Rule 5: Always specify return type explicitly even though default type is int.51

Rule 6: Do not return pointer and reference to local variable.51

Rule 7: Always call static method using CLASSNAME::[static method] format.52

Rule 8: Do not use inline method when they are not really needed53

Rule 9: Do not create method that have more than seven arguments.53

Rule 10: Always include a white space after a comma.54

Rule 11: Do not add a white space after method name when calling method.54

Rule 12: Do not use unspecified arguments ().55

13. Class Convention55 Rule 1: Should declare public, protected and private in this order and only one time.55

Rule 2: Always order items in an access section.56

Rule 3: Do not place anything in protected section except base class.57

Rule 4: Do not place member variables in public access section.58

Rule 5: Always initialize all class member variables in initialization list.59

Rule 6: Always ensure the order of variables in declaration and in init list are the same60

Rule 7: Always make base class destructor virtual60

Rule 8: Mark virtual for method in derived class when method is virtual in base class62

Rule 9: Do not let compiler generate default constructor.62

Rule 10: Should declare a copy constructor and assignment operator.63

14. Header and Implement Files Convention65 Rule 1: Do not include unnecessary header file.65

Rule 2: Should not use path in #include statement.65

Rule 3: Should not put methods implementation in header file even inline method.66

Rule 4: Should separate inline methods definition from implementation.67

Rule 5: Always use forward declaration instead of #include if possible.68

Rule 6: Dont define non-static variable in header file except constant variable.70

Rule 7: Do not define an aggregate variable or member in a header file even constant.70

Rule 8: Always separate each class from specific header and implementation files.71

15. Class Design Convention73 Rule 1: Should consider the following class design checklist as critical need.73

Rule 2: Should use destructor to prevent resource leaks.73

Rule 3: Should avoid resource leaks in constructors.75

Appendix: C++ Keywords79

1. Introduction

1.1 Purpose

This document defines C/C++ Coding Standards. These standards lead to consistency and help software engineers avoid common problems. A development environment that uses C/C++ standards has the following advantages:

Developers can view any C/C++ software and quickly figure out whats going on.

Developers new to C/C++ are spared the need to develop a personal style.

Developers make fewer mistakes in consistent environments.

Discussions about the appropriateness of software are reduced at reviews.

These guidelines are expected to be adhered to in all future C/C++ software development for the project. Existing code will not be required to be rewritten to adhere to these guidelines, but it is suggested that reasonable efforts are made to adhere to the new guidelines when working on existing code.

1.2 Scope

This document is written specifically for all project of TMA coding in C/C++ language, so it is meant to be as generic as possible. Because each project can have its own programming standard, so we can change this standard to be consistent with customer requirements.

In any case, the standard cannot cover every issue of C++ programming, and cannot always match the different choices that different experiments/projects have made on certain issues. Therefore the different experiments/projects should, if necessary, tailor this standard to their specific quality requirements; this could mean to suppress an item or to add additional items.

Each section of this document contains recommended standards in that area, along with a further list of guidelines. A standard is required to be followed in all future development. If a programmer must violate a standard, then the reason for doing so must be strong and clearly documented via code comments. Guidelines are just that.

Individual programmers are encouraged to program in a style which is consistent with the rest of the programming team, but differing code styles could be acceptable.

These standards recognize that individual programmers have the right to make judgments about how best to achieve the goal of code clarity. When working on others code, please respect and continue existing styles which, although they may differ from your own, meet these guidelines. This in turn leads to what is perhaps the most important aspect of coding style: consistency. Try as much as possible, to use the same rules throughout the entire program or module.

1.3 Definitions, Acronyms and Abbreviations

SPISoftware Process Improvement.

ItemSingle statement addressing a specific issue.

StandardCollection of items addressing the same subject.

ISOInternational Standard Organization

CMMCapability Maturity Model

OOPObject Oriented Program

1.4 References

[1] Optivity Telephony Manager C++ Coding Standards Kyle Blaney 2002/05/10

[2] Coding Standard (Volume Visual C++) 2002/08/07

[3] C++ Coding Standard Specification S.Paoli 2000/01/05

[4] C++ How to Program 3rd Dr. Harvey M. Deitel and Paul J.Deitel 2001 [5] More Effective C++ Scott Meyers 1996

[6] HotDocument tool for C/C++ comment conventions

2. Overview

This document is organized to many sections. In every section, the rules are formatted as following form:

Rule ##: Name of rule.

DescriptionThis rule is ONLY applied for specific cases or accepted from SOME.

JustificationWhy we use this rule?

ExampleGive out lines of sample codes which explain to the rule.

Comment Convention: In this section, you stand a good chance to learn how to comment software meet the standard.

Naming Convention: Name is called, its said that an intent name is considered carefully before naming. So why we have not to make a standard name? In this section, you will learn how to name a variable, a method, a class and so on.

Format Convention: Studies have shown that developers have strong expectations about what software should look like. With format convention your software will be neat and look professional.

Constant Convention: The purpose of this section is to name constant consistently.

Operator Convention: Just at a glance, this section is to give a form of operators should follow.

Control Flow Convention: In section, you will learn samples of control flow and something you should avoid.

Expression Convention: Expression is combination of operators, its operands and others. Every operator has its priority. As developer you have a lot of things to remember. Why you must put this mess thing in your mind. Following these rules in this section, you can be easy to recognize the processing order of expression. And avoid some unexpected errors!

Pointer and Memory Management Convention: Memory management is endless matter of C++ language. How to overcome this matter? You can recognize easily how to do in this section.

Variable and Data Type Convention: Variable is not dropped out. Yes, but you have to utilize its steps as much as possible. This section is to improve ways of using variable and data type as well.

Method Convention: You can be easy to know that method is the core of OOP. C++ is a strong language supporting OOP. So method convention is a need of C++ coding standard. In this section, you will learn how to organize your methods effectively.

Class Design Convention: The purpose of this section is to give out valuable ideas that you can take it together when designing class.

Rule 0: Every time a rule is broken, this must be clearly documented.

3. Comment Convention

Rules in this section ensure that software is formatted in a consistent comment. Following these rules, it is easy for fixers to fix potential bugs and for designers to upgrade production. The following are rules talking about comment.

Rule 1: Always use documentation comment immediately before declaration.

DescriptionApply to interfaces, class, member function, and field.

JustificationThis rule exists to create external documentation for a class.

ExampleThe following are samples:

For method:

/**

* ----------------------------------------------------------------

* Method Name:

* Description:

* @Params:

* @Return:

* @Exception:

* Note:

* ----------------------------------------------------------------

*/

For class:

/**

* -------------------------------------------------------------

* Class Name:

* Description:

* Copyright: Copyright (c)

* Company:

* @author:

* @version

* Note:

* -------------------------------------------------------------

*/

For function (Use HotDocument tool)

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

//

// Function Name : pStrInstr

//

// Description : Return index of character in string

//

// Return Values : - index of character

// -When character not exists, return 0

// Notes : pStrInStr( "a#c#d#eeee", "#" ) -> 2

// pStrInStr( "a#c#d##eeee", "##" ) -> 6

// pStrInStr( "abcdeabcde", "AA" ) -> 0

//

// Authors : BillGates

//

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

int pStrInStr(const char *tarstr, // Search target string

const char *srcstr) // Search string

{

return 0;

}

Rule 2: Do not use C-Style comment.

DescriptionApply to all objects.

JustificationSometime you want to temporarily turn it off somehow while debugging.

ExampleThe following do not comply:

/*

This code was commented out by Bang Mai on Feb 21, 2002.

CR: 009999

Area: WINCS

*/

- Avoid Block style comments.

Block Style:

/*

* .................... AVOID THIS!

* ..................... AVOID THIS!

*/

Please look in the other rules in this section for more information

Rule 3: Always use comment with //.

DescriptionApply to section of code, and declaration of temporary variable.

JustificationThis rule is to make clear what section of code does and what temporary variables purpose is.

ExampleThe following comply:

//This section is to update all systems.

// Get list of systems

int i_size = GetSize();

for (int i = 0; i < i_size; i++)

{

// Get type of current system

int i_type = GetType();

// Execute survivable cabinet system

if (i_type == 0)

{

}

// Execute main M1 system

else if (i_type > 0)

{

}

// Execute CSE system

else

{

}

}

Please look in the other rules in this section for more information

Rule 4: Do not leave commented out software in a file.

DescriptionApply to all objects.

JustificationCommented out software obscures behavior. If developers fail to notice that a block of software is commented out, they will misunderstand the softwares behavior. In addition, it is difficult for a file comparison tool to get an accurate representation of the changes made when software is commented out. To the file comparison tool, it appears that one section of software was modified and another section was added. This is not what actually happened. Rather, only one section was modified.

Sometimes, old versions of software are left (commented out) in a file so that a reader can have an idea of the history of changes to the file. This should not be done because maintaining a history of changes is a job already performed by a projects software revision control system(Source Safe, Clear Case, and so on). There is no reason to duplicate the effort of this tool.

ExampleThe following comply:

typedef void (FAR *MDRCorpdbTypes)(LPCTSTR);

The following do not comply:

// typedef void (FAR *RTCToIM)(LPCTSTR, char *);

typedef void (FAR *MDRCorpdbTypes)(LPCTSTR);

Rule 5: Do not include anything except description in comment.

DescriptionApply to all objects.

JustificationComments that indicate when and by whom software was changed are not necessary because that information is stored by the revision control system.

ExampleThe following do not comply:

// This code was commented out by Bang Mai on Feb 21, 2002.

// CR: 009999

// Area: WINCS

// This section is to execute background service for Web component.

The following comply:

// This section is to execute background service for Web component.

Rule 6: Do not put comment at the end of line.

DescriptionApply to all comments EXCEPT intentional fall-through in case statements or other table-based software, and #include statements.

JustificationEndline comments have the following problems:

It takes time to align them.

They are difficult to maintain. If the software on any line containing an endline

comment grows, it may push the comment out further, and all the nearby endline

comments may also require modifications.

It is hard to write a meaningful comment for a single line of software.

ExampleThe following comply:

// We shift by 6 bits because 2 ^ 6 = 64.

const unsigned int numBitsToShift = 6;

num