Programming specification (January 11, 2016)

Source: Internet
Author: User
Tags arithmetic operators case statement constant definition

I. Structure of the document
1.1 Copyright and Copyright notices
(1) Copyright information.
(2) file name, identifier, summary.
(3) Current version number, author/modifier, completion date.
(4) Version history information

1.2 Structure of the header file
(1) Copyright and copyright notice at the beginning of the header file.
(2) Preprocessing block.
A. In order to prevent the header file from being repeatedly referenced, a preprocessing block should be produced using the IFNDEF/DEFINE/ENDIF structure.
B. Use the #include<xx.h> format to refer to the standard header file (the compiler will start the search from the standard library directory).
C. Use the # include "xx.h" format to reference non-standard header files (the compiler will start searching from the user's working directory).
(3) Functions and class structure declarations, and so on.
A. Only "Declarations" are stored in the header file without "definition"
B. Do not advocate the use of global variables, try not to appear in the header file like externa into value such a declaration

1.3 Defining the structure of a file
(1) Define the copyright and version statement at the beginning of the file.
(2) A reference to some header files.
(3) The implementation body of the program (including data and code).

1.4 The role of the header file
(1) The library function is called through the header file.
(2) header file can enhance type safety check.

1.5 Directory structure
Typically, the header and definition files are saved in separate directories for easy maintenance. Put the relevant things together as much as possible.
The Include directory is the API function definition that provides services to the outside, and the definition of the data structure.
SRC directory to put the original program.
Doc release documentation.
Test catalog put and tested examples
The intermediate definition of the Inlude file can be placed in SRC, if the src is divided into multiple subdirectories, it can also be placed in a sub-directory

Second, the version of the program
2.1 Blank Line
A. After each class declaration, add a blank line after the end of each function definition, and the other places should be separated by a blank line.
B. In a function body, there is no empty line between the logically closely related statements, and the other places should be separated by a blank line.

2.2 Line of code
A. A line of code only does one thing, such as defining only one variable, or just writing a single statement. The code is easy to read and easy to annotate.
The statements of B.if, for, while, and do are only one row, and the execution statements must not be followed.
Recommendation: Initialize the variable as much as possible while defining the variable (nearest principle)

2.3 Spaces within lines of code
A. Leave a blank after the keyword.
B. Do not leave a blank after the function name, followed by the opening parenthesis, to distinguish it from the keyword.
C. ' (' back immediately, ') ', ', ', '; ' Move forward, followed by a blank space.
D. ', ' after which you want to leave a blank, such as function (x, y, z). if '; ' is not a line ending symbol, then a blank cell.
E. Assignment operators, comparison operators, arithmetic operators, logical operators, bit field operators, and so on before and after the two-dollar operator should be preceded by a space.
F. Unary operators and so on without spaces.
G. Such operators as "[]", ".", "and" are not preceded by spaces.
H. For statements with long expressions and if statements, some spaces can be suitably removed for the sake of compactness.
The above suggestions are not absolute.

2.4 Alignment
A. The program's delimiter ' {' and '} ' should be exclusive to one row and be in the same column, with the statement that references them left-justified.
Code blocks within b.{} are left aligned at the right of the ' {'.

2.5 Long lines of split
A. The maximum length of the code line should be controlled within 70 to 80 characters.
B. Long expression to be split into a new line at a low priority operator, the operator is placed at the top of the new line.

The position of the 2.6 modifier
A. Modifiers * and & should be close to the variable name

2.7 Notes
A. A comment is a "hint" to the code, not a document.
B. If the code is clear, you do not need to comment.
C. Side write code side comments, modify the code at the same time to modify the corresponding comments to ensure that the comments and code consistency.
D. Comments should be accurate and understandable to prevent the annotation from being two semantic.
E. Try to avoid abbreviations in annotations, especially those that are not commonly used.
F. The location of the note should be adjacent to the code being described.
G. When the code is longer, especially when there are multiple nesting, it should be filled in at the end of some paragraphs.

Layout of Class 2.8
Two kinds:
(1) write the private type of data in front, and write the function of the public type behind
A. Programmers using this layout argue that the design of the class is "data-centric" and focuses on the internal structure of the class.

(2) Write the function of the public type in front, and write the private type data behind
B. Programmers using this layout argue that the design of the class is "behavior-centric" and focuses on what interfaces the class should provide.

Third, naming rules
3.1 Common rules
A. Identifiers should be intuitive and can be spelt out, and it is expected that the text should be understood without "decoding".
B. The length of the identifier should conform to the "Min-length && max-information" principle.
C. The naming convention should be consistent with the style of the operating system or development tool used.
D. Do not appear in the program similar identifiers that are only case sensitive.
E. Do not have local variables and global variables with identical identifiers, although the scope of the two is different and there is no syntax error, but it can be misleading.
F. The name of the variable should use "noun" or "adjective + noun".
G. The name of the global function should use "verb" or "verb + noun" (moving-in phrase).
The member function of a class should use only "verbs", and the omitted noun is the object itself.
H. Naming a variable with a mutually exclusive meaning or a function of the opposite action with the correct antonym group
I. Try to avoid the number of numbers in the name, such as Value1,value2, unless the number is logically required.

3.2 Simple Windows Application Naming conventions
A. Class name and function name are combined with words that begin with uppercase letters.
B. Variables and parameters are combined with words that begin with lowercase letters.
C. Use all uppercase letters and use underscores to divide the words.
d. Static variable plus prefix s_ (for static).
E. If a global variable is required, prefix the global variable with g_ (representing global).
F. The data member of the class is prefixed with m_ (for member), which prevents the data member from having the same name as the parameter of the member function.
G. In order to prevent conflicts in some identifiers and other repositories in a software library, you can add prefixes that reflect the nature of the software for a variety of identifiers.

Iv. Expressions and Basic statements
Precedence of the 4.1 operator
A. If there are more operators in the line of code, use parentheses to determine the order of operations of the expression, and avoid using the default precedence.

4.2 Composite Expressions
A. Do not write complex expressions that are too complicated.
B. Do not have multi-purpose composite expressions.
C. Do not confuse the compound expression in the program with the "true mathematical expression".

4.3IF statements
4.3.1 Boolean variable versus 0 value comparison
A. You cannot compare Boolean variables directly with True, false, or 1, 0.

4.3.2 Integer variable versus 0 value comparison
A. You should use the integer variable with "= =" or "! = "Compare directly with 0.

4.3.3 floating-point variable versus 0-value comparison
A. Do not use the floating-point variable "= =" or "! = "Compared to any number.

4.3.4 pointer variable compared to 0 value
A. You should use the pointer variable "= =" or "! = "Compared to NULL.

4.4 Efficiency of the Loop statement
For statements use the most frequently, while statements second, do statements are seldom used. The basic method to improve cycle efficiency is to reduce the complexity of the loop body.
A. In multiple loops, if possible, the longest loop should be placed in the outermost layer, with the shortest loop at the top, to reduce CPU cross-cutting if the number of rings in the loop body
B. If there is a logical judgment in the loop and the number of cycles is large, it is advisable to move the logical judgment outside the loop body.

loop control variables for 4.5FOR statements
A. You cannot modify the loop variable inside the for loop to prevent the for loop from losing control.
B. Recommend that the value of the loop control variable for the For statement be used as the "half open half closed interval" notation

4.6switch statements
A. Do not forget to add a break at the end of each case statement, or it will cause multiple branches to overlap (unless you intentionally overlap multiple branches).
B. Don't forget the last default branch. Default:break;

4.7goto statements
Accidental processing can be used backwards goto, but to arrange the appropriate processing points, the general first define the processing point, and then Goto.


Five, constant
5.1 Why constants are required
A. Try to use a represented that is intuitive to represent numbers or strings that will appear more than once in a program.

Comparison of 5.2const and # define
A. Only const constants are used in C + + programs without using macro constants, that is, const constants completely supersede macro constants.

5.3 Constant Definition Rules
A. Constants that need to be exposed are placed in the header file, and the constants in the definition file do not need to be exposed externally.
For ease of management, the constants of different modules can be centrally placed in a common header file.
B. If a constant is closely related to other constants, the relationship should be included in the definition, and no isolated values should be given.

Constants in the 5.4 class
You cannot initialize a const data member in a class declaration. The initialization of a const data member can only be done in the initialization table of the class constructor.
How can you build constants that are constant throughout the class?
A: Do not expect the Const data member to be implemented with enumeration constants in the class.
ENUM{A=100,B=200}; Enumeration constants do not consume the object's storage space and are evaluated at compile time.
The disadvantage of enumeration constants is that the implied data type of stepping is an integer, its maximum value is limited, and it cannot represent a floating-point number.

VI. function design
6.1 Rules for parameters
A. The writing of parameters should be complete, do not want to be easy to write only the type of parameter and omit the parameter name. If the function has no arguments, it is filled with void.
B. The name of the parameter should be appropriate, the order should be reasonable.
C. If the parameter is a pointer and is only used for input, you should add a const before the type to prevent the pointer from being accidentally modified in the function body.
D. If the input parameter passes the object as a value, it should be passed using the "Const &" method, which saves the construction and destruction of the temporary object, thus improving efficiency.
E. Avoid the function has too many parameters, the number of parameters as far as possible to control within 5.
F. Try not to use parameters of type and number uncertainties.

6.2 Return Worthy rules
A. Do not omit the type of the return value.
B. The function name and return value type are semantically non-conflicting. such as: GetChar () is not a char type but an int type.
C. Do not mix the normal values and the error flags back together. The normal value is obtained with an output parameter, and the error flag is returned with a return statement.
D. Sometimes the function does not originally need to return a value, but in order to increase flexibility, such as support chain expression, you can append the return value.
E. If the return value of a function is an object, there are occasions where the use of "reference passing" to replace "value passing" can improve efficiency.
Some situations can only be passed with "value" and not "referenced", otherwise an error occurs.

6.3 Rules for internal implementation of functions
A. In the "entrance" of the function body, check the validity of the parameters.
B. At the "exit" of the function body, check the correctness and efficiency of the return statement.

6.4 Other recommendations
A. Function functions should be single, do not design multipurpose functions.
B. The size of the function is small, try to control it within 50 lines of code.
C. Try to avoid functions with "memory" function. The same input should produce the same output. It is recommended that you use static local variables sparingly.
D. Not only to check the validity of input parameters, but also to check the validity of variables entering the function body by other means, such as global variables, file handles, etc.
E. The return value for error handling must be clear so that readers are not easily overlooked or misunderstood.

6.5 Using assertions
If the program terminates at the assert, not saying that the function containing the assert has an error, but that the caller has made a mistake, the assert can help us find the cause of the error.

6.6 Comparison of references to pointers
A. References are created at the same time must be initialized (pointers can be initialized at any time).
B. You cannot have a null reference, and the reference must be associated with a valid storage unit (the pointer can be null).
C. Once a reference is initialized, the referenced relationship cannot be changed (the pointer can change the object at any time).

Seven, memory management
7.1 How to allocate memory
A. Assign from a static storage area.
B. Create on the stack.
C. Allocation from the heap, also known as dynamic memory allocation.

7.2 Common memory errors and their countermeasures
Common errors:
A. The memory allocation was unsuccessful, but it was used.
B. The memory allocation succeeds, but it is not initialized to reference it.
C. The memory allocation succeeds and has been initialized, but the operation crosses the memory boundary.
D. Forget to release memory, causing memory leaks.
E. Freed up memory but continues to use it.

Countermeasures:
A. After requesting memory with malloc or new, you should immediately check that the pointer value is NULL. Prevents the use of memory with a pointer value of NULL.
B. Do not forget Fu Yan values for arrays and dynamic memory. Prevents the initialized memory from being used as the right value.
C. Avoid array or pointer subscript out of bounds, especially beware of "more than 1" or "less 1" operation.
D. Application and release of dynamic memory must be paired to prevent memory leaks.
E. After releasing memory with free or delete, set the pointer to null immediately, preventing the "wild pointer" from being produced.

7.3 Comparison of pointers to arrays
7.3.1 Modifying content
The contents of a constant string cannot be modified.

7.3.2 Content Replication and comparison
You cannot copy and compare directly to an array.

7.3.3 Computer Memory capacity
Note that when an array is passed as an argument to a function, the array is automatically degraded to a pointer of the same type.

7.4 How the pointer parameter is passed in memory
If the parameter of the function is a pointer, do not expect to use the pointer to apply dynamic memory.

7.5free and delete
They simply release the memory that the pointer refers to, but do not kill the pointer itself.

7.6 Will the dynamic memory be released automatically?
Local variables in the function body die automatically at the end of the function.
(1) The pointer dies, and does not mean that it is automatically released in the memory it refers to.
(2) The memory is freed, and does not mean that the pointer dies or becomes a null pointer.

7.7 Eliminate "wild hands"
The "Wild pointer" is not a null pointer, it is a pointer to "junk" memory.
There are two main causes of the "wild pointer":
A. Pointer variables are not initialized.
B. After the pointer p is free or delete, it is not set to NULL, which makes the person think that P is a valid pointer.
C. Pointer manipulation goes beyond the scope of the variable.

7.8 Why do you want to new/delete with Malloc/free?
malloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +.
The constructors and destructors are not included in malloc and free.

7.9 How to run out of memory
If a large enough block of memory is not found when the memory is requested, malloc and new will return a null pointer declaring the memory request to fail.
Three ways to handle:
A. Determine if the pointer is null, and if so, terminate the function with the return statement immediately.
B. Determine if the pointer is null, and if so, immediately terminate the entire program with exit (1).
C. Set exception handling functions for new and malloc.

7.10 Some experience
A. The more you fear the pointer, the more you use the pointer. Not using pointers correctly is definitely not a qualified programmer.
B. The habit of "using the debugger to track programs gradually" must be developed in order to discover the nature of the problem.

Viii. advanced Features of C + + functions
8.1 Overloading, overwriting, hiding
Features of overloading:
A. The same scope (in the same class);
B. The function has the same name;
C. different parameters;
d.virtual keyword is optional.

Overrides refer to a derived class function overriding a base class function, characterized by:
A. Different scopes (in the derived class and the base class, respectively);
B. The function has the same name;
C. the same parameters;
D. The base class function must have the virtual keyword.

Hide rule:
Hiding refers to a function of a derived class that masks a base class function with the same name
A. If a function of a derived class has the same name as a function of a base class, the parameters are different. At this point, the functions of the base class will be hidden, regardless of the virtual keyword (be careful not to be confused by overloading).
B. If the function of the derived class has the same name as the function of the base class, and the parameters are the same. However, the base class function does not have the virtual keyword. At this point, the function of the base class is hidden (be careful not to be confused by overrides).

Xi. Efficiency Issues
Do not blindly pursue the efficiency of the program, should be satisfied with the correctness, reliability, robustness, readability and other quality factors under the premise of trying to improve the efficiency of the program.
To improve the overall efficiency of the program as the main, improve local efficiency supplemented.
In optimizing the efficiency of the program, you should first identify the "bottleneck" of limiting efficiency, and do not optimize it in irrelevant areas.
Optimize the data structure and algorithm, and then optimize the execution code.
Do not ask for the most compact code, because the compact code does not produce efficient machine code.

Programming specification (January 11, 2016)

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.