I personally summarized some C/C ++ coding standards

Source: Internet
Author: User
Tags coding standards

I personally summarized some C/C ++ coding standards

For different programming languages, the specific encoding specifications can be very different, but their purposes are consistent, it is to ensure that the Code meets the requirements of high quality and has good readability and maintainability. For example, we can stipulate that the C language program of a project should follow the following rules: variable naming, header file writing and#includeAnd so on.

Below are some widely used encoding specifications:

GNU Coding Standards Guidelines for the Use of the C Language in Vehicle Based Software C ++ Coding Guidelines SUN Code Conventions for Java

The following are some books about coding and coding standards:

C ++ coding specifications, Chen shizhong, people's post and telecommunications Publishing House, 2002 high quality programming guide: C ++/C language, Lin Rui, e-Industry Publishing House, 2003

Note: The following is a summary based on the existing experience of the research team. It is not applicable to all scenarios.

For high-quality projects, we generally do the following:

The code is concise, elegant, readable, highly efficient, reusable, portable, high cohesion, low coupling, no redundancy, and does not comply with these principles. Normative and code-compliant. Special typographical, special syntax, and special instructions must be specified.

I. File Layout

Include header files
1.1 first the system header file and then the user header file.
1.2 The system header file and a stable directory structure should contain sub-paths.
1.3 custom header files with unstable directory structures should be included in the dsp.
1.4 system header file application:#include
1.5 customize the same file application:#include "xxx.h"
1.6 Only reference the required header file.

H and cpp files
2.1 name the header file*.hInline file named*.inlThe C ++ file is named*.cpp
2.2 mix file names in case or lower case. For exampleDiyMainView.cpp,infoview.cpp. Do not use meaningless names: for exampleXImage.cpp;SView.cpp;xlog.cpp;
2.3 In addition to special cases, the header file should be used#ifdefControl Block.
2.4 header files#endifLine End comments should be used.
2.5 The header file first contains the code block, followed by the macro-defined code block, followed by the global variables, global constants, Type Definitions, class definitions, and inline sections.
2.6 CPP file, including commands, macro definitions, global variables, and function definitions.

File structure
3.1 The file should contain the file header comments and content.
3.2 In principle, two empty rows are used between function bodies. In special cases, one or no empty rows are available.

Empty row
4.1 file header, control block,#includePart, macro definition part,classTwo empty rows are used between functions, global constants, global variables, and functions.

Ii. Comments

File Header comment
1.1 author, file name, file description, generation date (optional)

Function comments
2.1 key functions must be annotated to describe the functions.
2.2 for special function parameters, it is necessary to describe the purpose of the parameters and who is responsible for releasing them.
2.3 except in special cases, do not place comments before the code line.
2.4 for each#elseOr#endifComment the end of the trip.
2.5 key code comments, including but not limited to assignment, function call, expressions, and branches.
2.6 Add// TODO ...
2.7 add comments to the Code for debugging// only for DEBUG
2.8 add comments to the code that requires attention// NOTE ...
2.9 for the end of a large code block, suchfor,while,doAnd so on.// end for|while|do

Iii. Naming

Principles
1.1 identity: When writing a submodule or a derived class, you must follow the naming style of its base class or overall module to maintain the identity of the naming style in the entire module.
1.2 identifier composition: identifiers use English words or their combinations. They should be intuitive and can be spelled out. They are expected to understand and use accurate words to avoid naming in pinyin.
1.3 principle of minimizing length & maximizing the amount of information: the length of an identifier should be minimized while its meaning is clear.
1.4 avoid being too similar: do not show similar identifiers, such"i"And"I","function"And"Function"And so on.
1.5 avoid duplicate names in different scopes: do not show local variables and global variables with identical names in the program, even though they have different scopes without syntax errors, but it is easy to misunderstand.
1.6 correctly naming mutex-specific identifiers: use the correct antgroup to name mutex-specific identifiers, such:"nMinValue"And"nMaxValue","GetName()"And"SetName()"....
1.7 avoid numbers in the name: Avoid numbers in the name, as shown in figureValue1,Value2And so on, unless the number is required logically. This is to prevent programmers from being lazy and refuse to name their brains, resulting in meaningless names (because numbers are the most convenient ).

T, C, M, R class
The 2.1 T class indicates a simple data type. It does not have control over the resource and does not release the resource during the analysis process.
2.2 C indicates the class inherited from CBase. This class cannot define variables from stacks, but can only be created from stacks.
2.3 M indicates the interface class.
2.4 R is a resource class, usually inherent in the system. Except for special cases, the R type should not appear in the development code.

Function Name
3.1 M class function names should be usedHandleXXXName, for example:HandleTimerEventJava is not recommended, for examplehandleTimerEventIn addition to standard c-style code, underlines are not recommended. For example,handle_event.
3.2 Leave function, with the suffix L.
The 3.3 Leave function is used to clear the stack and use the suffix LC.
3.4 Leave function. Delete the object with the suffix LD.

Function Parameters
4.1 function parameters use a as the prefix.
4.2 avoid mixed naming rules suchapBufferName. UseaBufferYou can.
4.3 if there are many function parameters, you should consider replacing them with a structure.
4.4 If you cannot avoid too many function parameters, you should consider that each parameter occupies one row in the layout, and the parameter names are vertically aligned.

Member variables
5.1 member variables are prefixed with m.
5.2 avoid mixed naming rules suchmpBufferName. UsemBufferYou can.

Local variable
6.1 use a simple lowercase string for loop variables and simple variables. For example,int i;
6.2 for pointer VariablespHeaders, suchvoid* pBuffer;

Global Variables
7.1 use global variablesg_The most prefix.

Class Name
8.1 class and object names should be nouns.
8.2 The Name Of The class member function implementing the behavior should be a verb.
8.3 class access and query member function names should be nouns or adjectives.

Style compatibility
9.1 for transplanted or open-source code, the original style can be used without the naming rules of C ++.

Iv. Code style

Tab and Space
1.1 The indentation at the beginning of each line can only be Tab, but cannot be blank. After the content is entered, all spaces are used. In addition to tabs for the initial indent control, spaces must be used to indent the other parts for alignment. This prevents non-alignment in different editors.
1.2 no extra spaces are allowed at the end of the code line.
1.3 do not"::","->","."Add a space before and after.
1.4 do not",",";"Add a space.

Type Definition and {
Class 2.1, structure, enumeration, Union: braces start with another line

Function
{Of the 3.1 function body requires a new line, and there cannot be indentation before.
3.2 except in special cases, there cannot be two blank rows in the function body.
3.3 except in special cases, macro-defined commands are not allowed in the function body.
3.4 In a function, there are no empty rows between closely related statements on the zookeeper. Separate empty rows in other places.
3.5 defined in the header fileinlineFunction. Empty rows are not required between functions. We recommend that you use a blank row.

Code block
4.1"if"、"for"、"while"、"do"、"try"、"catch"When a statement occupies one row, the execution statement cannot be followed by it. No matter how many statements are executed, add"{ }". This prevents mistakes in writing and modifying code.
4.2"if"、"for"、"while"、"do"、"try"、"catch"Brackets and expressions. Brackets can be placed next to keywords, which emphasizes expressions.

Else
5.1 if statements with else statements are written as one line by using} else {. It is not recommended to use three lines of code.

Code line
6.1 a line of code only does one thing, such as defining only one variable or writing only one statement. Such code is easy to read and easy to write comments.
More than 6.2 lines of variable definitions, in order to pursue the beautiful code layout, the variables can be vertically aligned.
6.3 The maximum length of a code line should be limited to a certain number of characters, and it is recommended to be visible in the current screen.

Switch statement
7.1 The case keyword should be aligned with switch.
7.2 if the case substatement contains a variable, the application {} is included.
7.3 If there are parallel simple case statements, you can consider writing the case code block as a line of code.
7.4 empty rows are not required between simple cases. In complicated cases, empty rows should be used for separation.
The braces of the 7.5 case statement start with another line. Do not write a line with the case statement.
7.6 provide the default branch for all switch statements.
7.7 If a case does not require break, you must add comments to the Declaration.

Loop
8.1 empty loop availablefor( ;; )Orwhile( 1 )Orwhile( true )

Class
9.1 class inheritance should use the method in which each base class occupies a row.
9.2 single inheritance can place the base class in the same row defined by the class. If multiple rows are used, Tab indentation is applied.
If the base class is more than 9.3 inherited, the base class branch should be aligned with Tab indentation.
9.4 to overload the base-class virtual function, you should write comments before this group of virtual functions.// implement XXX
The $9.5 statement is placed at the end of the class.

Macro
10.1 do not end the macro definition with a semicolon.
10.2 every parameter of the FUNCTION macro must be included.
10.3 macro functions without parameters must also be defined as functions.

Goto
11.1 do not use goto.

V. Type

When defining pointers and references *And &Keep up with type. Do not use floating point numbers unless necessary. Use typedefSimplify the complex syntax in the program. Avoid defining a type without a name. For example: typedef enum { EIdle, EActive } TState;Use less unionIf necessary, simple data type members are used. Use enumReplace (a set of related) constants. Do not use devil numbers. Replace pointer with reference whenever possible. Initialize the variable immediately after it is defined. Do not wait until it is used. If you have a more elegant solution, do not use forced type conversion.

Vi. Expressions

Avoid using value assignment statements in expressions. Avoid determining whether the floating point type is equal to or not equal. Enumeration types cannot be assigned to enumeration variables after calculation. Do not modify the counter during the loop process. Detects null pointers. if( p )Detects non-null pointers. if( ! p )

VII. Functions

Reference
1.1 reference type as return value: the function must return an existing object.
1.2 reference type as a parameter: The caller must pass an existing object.

Constant member functions
2.1 indicates that the function only reads the object content and does not modify the object.

Return Value
3.1 deactivatingvoidFunction, constructor, destructor, and other functions must return values.
3.2 When a function returns a reference or pointer, use text to describe its validity period.

Inline functions
4.1 inline functions should put the function body in the class body.
4.2 only simple functions are required to be designed as inline functions. Do not design functions with complex business logic.
4.3 do not design virtual functions as inline functions.

Function Parameters
5.1 read only the content of this parameter, do not modify its content, and use constant reference.
5.2 modify the parameter content, or return the result through the parameter, and use a very large number of applications.
5.3 simple data types are passed through values.
5.4 complex data types are referenced or pointers.

Class 8

Constructor
1.1 The initialization list of the constructor should be consistent with the class order.
1.2 each item in the initialization list should have an exclusive row.
1.3 avoid using one member to initialize another member.
1.4 The constructor should initialize all Members, especially pointers.
1.5 do not throw an exception in constructor and destructor.

Pure virtual functions
Virtual functions of the 2.1 M class should be designed as pure virtual functions.

Constructor and destructor
3.1 If the class can be inherited, you should design the class destructor as a virtual function.
3.2 If the class cannot be inherited, you should design the class destructor as a non-virtual function.
3.3 If the class cannot be copied, the copy constructor and value assignment operator should be designed to be private.
3.4 If the constructor is designed for the class, the constructor should be used.

Member variables
4.1 avoid usingmutableAndvolatile.
4.2 avoid using public member variables whenever possible.

Member Functions
5.1 strive to make the class interfaces less and complete.
5.2 use a common member function instead of a non-member function as much as possible,constFunction
5.3 unless otherwise specified, do not redefine (inherited) Non-virtual functions. (In this case, some attributes of the base class are not initialized)

Inheritance
6.1 inheritance must satisfy the IS-A relationship and the HAS-A should adopt inclusion.
6.2 do not use default parameters for virtual functions.
6.3 avoid designing large and comprehensive virtual functions unless otherwise required. The virtual functions should be single.
6.4 avoid forcibly converting a base class to a derived class unless otherwise required.

Youyuan
7.1 avoid using friend functions and friend classes whenever possible.

9. handle errors

Apply for memory usage newOperator. Release memory deleteOperator. newAnd delete, new[]And delete[]In pairs. After the memory application is complete, check whether the pointer application is successful and process the application failure. Who applies for release. Priority: function level, class level, and module level. After the memory is released, the pointer is null to avoid the occurrence of a wild pointer. The validity of the judgment should be taken into account when the pointer is used. When using arrays, you should first determine the validity of indexes and handle invalid indexes. The Code cannot contain compilation warnings. Use the error handling idea of error transfer. Wei Sentence Style: First handle all possible errors and then handle normal situations. Nesting do-while(0)MACRO: The purpose is to convert a group of statements into one statement to avoid interruption by other if statements.

10. Performance

Use Forward Declaration instead #includeCommand. Class M;Try to use ++iReplace i++. Replace the suffix operation with a prefix. Try forBefore the loop, write the calculation value expression. Avoid defining objects in the loop body. Avoid copying objects, especially copying objects with high costs. Avoid generating temporary objects, especially large temporary objects. Pay attention to the array of large objects. 80-20 principles.

XI. Compatibility

Complies with ansi c and iso c ++ international standards. Make sure that no information is lost during type conversion. Note the compatibility of double-byte characters. Note the overflow problem. Do not assume the storage size of the type. Do not assume the Operation Sequence of the expression. Do not assume the order in which function parameters are calculated. Do not assume the initialization sequence of static or global variables in different source files. Do not rely on the compiler to implement, undefined, or undefined functions. Set all #includeThe file name is case sensitive. Avoid using global variables, static variables, function static variables, and class static variables. Compatibility problems may occur when static libraries, dynamic libraries, and multi-threaded environments are used. Do not implement standard library functions again, such as existing STL functions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.