High Quality C ++C Programming Guide Learning Notes (on)

zhaozj2021-02-17  56

High Quality C / C Programming Guide Learning Notes (on) Time: 2002/11/13 PM Li Jinfan

"High Quality C / C Programming Guide" is Lin Rui

Dr. wrote, it has already been booked. The following is some notes I am studying, and I have a short to see you.

1. Declaration on copyright and version

Copyright and version of the statement is located at the beginning of the header file and the definition file. Examples are as follows:

/ ** CopyRight (C) 2001, Shanghai Bell Co., Ltd. Network Application Division

* All Rights Reserved.

*

* File Name: filename.h

* File ID: See Configuration Management Program

* Summary: Summary describes the contents of this document

*

* Current version: 1.1

* Author: Enter the author (or modifier) ​​name

* Completion date: July 20, 2001

*

* Replacement version: 1.0

* Original Author: Enter the original author (or modifier) ​​name

* Completion date: May 10, 2001

* /

2. About header files

Ø In order to prevent the header files from being repeatedly referenced, the preparation block should be generated using the IFNDEF / DEFINE / ENDIF structure.

Ø Only "declaration" is stored in the header file without storing "definition", including the internal function, it is best to be placed in the definition file.

Ø Use global variables as little as possible, try not to appear in the header files Extern int value this category.

3, the management of the source code file

If a software's header file is more (such as more than ten), the header file and definition file should usually be saved in different directories for maintenance.

For example, the header file can be saved in the include directory, and the definition file is saved in the Source directory (which can be a multi-level directory).

If some headers are private, it is not directly referenced by the user, and it is not necessary to disclose its "declaration". In order to enhance information hidden, these private headers can be stored in the same directory and definition files.

4, the role of the blank line

After each class declaration, the rows must be added after each function definition.

In a functional body, the lack of space is not vacuum lines, and the line should be separated elsewhere.

5, code line

Ø One line code only does one thing, if only one variable is defined, or write only one statement. This code is easy to read and is convenient to write a comment.

Ø If, for, while, do, other words, the execution statement is not followed by it. No matter how much the execution statement is, {}. This prevents writing errors.

Ø Initialize this variable while defining variables

6, space in the code line

Everything is just to look good, just like writing. Words are poor, no one will say you, but it is not right.

Ø Don't leave the space after the function name, there are too many spaces that are more troublesome.

Ø Assignment operator, compare operator, arithmetic operator, logical operator, bit domain operator, such as "=", " ="> = "," <= "," "," * "," %, "&&", "||", "<<", "^", etc., the binary operator should be added.

Ø One dollar operator is like "!", "~", " ", "-", "&", "" & ", etc.

7. About alignment

The delimiter '{' and '}' of the program should be exclusive and located in the same column, while aligning the statement that references them.

8, long line split

The maximum length of the code line should be controlled within 70 to 80 characters. Don't be too long, otherwise you can't see it, it is not convenient for printing.

9, the location of the modifier should be modified * and & &

10, note

Ø Comment is the "prompt" for the code, not a document.

Ø For each function module, you need to note what functionality, the parameter description of the function.

Ø Not too much, too much will make people dazzle.

Ø It is very simple to note that it is very simple to note.

Ø Function annotations that need to be implemented for more complicated or more important code segments.

Ø Side of the write code, modify the code simultaneously modify the corresponding annotation to ensure the consistency of the comment and the code. Annotation that is no longer deleted.

Ø The annotation should be accurate, easy to understand, prevent the annotation of unity. The wrong note is not only harmful.

Ø Try to avoid using abbreviations in the comments, especially uncommonly.

Ø The position of the comment should be placed above or the right side of the code.

Ø When the code is longer, especially when there is multiple nested, it should be added at the end of some paragraphs to facilitate reading.

Ø When some reason is to shield some code segments, the reason, operation time, and operator should be taken on the shield code segment.

11, class layout

2 There are two arrangements, one is based on data, and the other is in the center of behavior.

2 Recommendation to place the PUBLIC's function or variable in front, Private places in the end.

12, naming rules

2 The identifier should be intuitive and can be spent, and it is desirable to know that "decoding" is not required.

2 The length of the identifier should comply with the principle of "min-length &&max-information".

2 Single character's name is also useful, common as i, j, k, m, n, x, y, z, etc., which can usually be used as partial variables within functions.

2 In the identifier of the Windows application, "case" mixing is usually used, such as addChild.

2 Do not appear only similar identifiers that only rely on case in size.

2 Local variable names best not to be the same as the global variable name

2 The name of the variable should use "noun" or "adjective noun".

2 The name of the global function should use "verb" or "verb noun" (mobile phonology group). The member function of the class should only use "verbs", and the noun omitted is the object itself.

2 Name the correct antonym group named mutually exclusive variables or function of oppositely.

2 Try to avoid digital numbers in the name, such as Value1, Value2, etc., unless logically required numbers.

2 The class name and function name are combined with the word starting with uppercase letters.

2 Variables and parameters are combined with a word of lowercase letters.

2 Constants use uppercase letters and segment words with underscore.

2 Static variable addequacy S_ (represents static).

2 If a global variable is not required, the global variable is prefixed G_ (represents Global).

2 The data member of the class adds M_ (represents member) so that the data member is the same name with the member function.

2 In order to prevent some identifiers in a single software library and conflicts in other software libraries, you can add a prefix that can reflect software properties for various identifiers. For example, all library functions of the 3D graphic standard OpenGL are starting with GL, all constants (or macro definitions) start with GL.

13, expressions and essentials

2 If the operators in the code line are more, use parentheses to determine the order of operations, avoid using the default priority.

2 Do not write too complicated composite expressions. 2 Do not have multi-purpose composite expressions.

2 Do not confuse the composite expression in the program with the "real mathematical expression".

2 Do not compare the Boolean variables directly with True, False or 1, 0.

2 Compare the integer variables with "==" or "! ="

2 Do not use "==" or "! =" With any numerical comparison with any number.

2 The pointer variable should be compared to NULL with "==" or "! =".

2 In a multi-cycle, if possible, the number of cycles should be placed in the innermost layer, and the least loop is placed in the outermost layer to reduce the number of CPU cross-cutting circulation layers.

2 Do not modify the loop variables in the FOR cycle to prevent the FOR loop from being lost.

2 Recommendation of the value of the loop control variable of the FOR statement is written in "semi-open semi-closed interval".

2 End of each CASE statement should not forget to add BREAK, otherwise multiple branch overlaps (unless you intend to overlap multiple branches).

2 Don't forget the last Default branch. Even if the program really does not need Default processing, the statement Default: Break should also be reserved. Do not do more, but to prevent others from mistaken to think that you forgot DEFAULT.

2 Use the goto statement as little as possible, but is not disabled.

14, constant definition rules

2 constants have two: one is constant, one is the constant defined with #define

2 CONST's Advantages: Const constants have data types, while the macro regular volume has no data type. Some integrated debugging tools can debug a Const constant, but cannot debug a macro.

2 Try to use constant to indicate those that will appear multiple times in the program.

2 There is a need to place the constant on the header file, and there is no need to place the heads of the definition file on the existing constant.

2 If a constant is closely related to other constants, this relationship should be included in the definition, and some isolated values ​​should not be given.

15. Constants in the class (all the abstracts, of course there is reason: because I will not)

Sometimes we hope that some constants are only valid in the class. Because the macroemulus defined by #define is global, it cannot achieve the goal, so it is to certainly feel that it should be implemented with a const modified data member. The Const data member does exist, but its meaning is not what we expect. Const data members are constants only within an object survival, but for the entire class, it is variable because the class can create multiple objects, and different objects can be different.

CONST data members cannot be initialized in class declarations. The following usage is wrong, because the compiler does not know what the value of size is not created.

Class A

{...

const Int size = 100; // Error, attempted to initialize Const data members in class declarations

INT Array [size]; // error, unknown SIZE

}

The initialization of Const data members can only be performed in the initialization table of the class constructor, for example

Class A

{...

A (int size); // constructor

CONST INT Size;

}

A :: A (int size): initialization table of size (size) // constructor

{

...

}

A a a (100); // // The size value of the object A is 100

A b (200); // The Size value of the object B is 200

How can I build constant constant in the entire class? Don't expect const data members, you should implement the enumeration constants in the class. For example, Class A

{...

ENUM {size1 = 100, size2 = 200}; // enumeration

Int Array1 [Size1];

Int array2 [size2];

}

Enumerations often do not take up the storage space of the object, and they are fully evaluated when compiling. The disadvantage of the enumeration is that its implied data type is an integer, its maximum value is limited, and cannot represent floating point numbers (such as PI = 3.14159).

16, function design

There are three parameters and return values ​​of the function of the function: Value Pass By Value and Packing (PASS BY Reference).

17, function parameter rules

2 The writing of the parameters should be complete, do not save the type of only the type of parameters and omit the parameter name, no parameters are functioning, and VOID fills.

2 Parameter naming should be appropriate, the order is reasonable. In general, the destination parameters should be placed in front, and the source parameters should be placed behind.

2 If the parameter is a pointer, it is only used for input, then CONST should be added prior to the type to prevent the pointer from being accidentally modified in the function.

2 If the input parameter is passed in value delivery, it can be transferred to the "const" mode, so that the temporary object constructs and destructive processes can be saved, thereby increasing efficiency.

18, function return value rules

2 The type of return value should be consistent with the type of function declaration.

2 Do not return normal values ​​and error signs to return. Normal values ​​are obtained with output parameters, and the error flag returns with the return statement.

19. Rules in the internal implementation of functions

In the "entrance" of the function, check the validity of the parameters.

In the "exit" of the function body, check the correctness and efficiency of the RetURN statement.

The variables within the function will be destroyed automatically, so don't return a pointer to the internal variable. This will be wrong. Such as

Char * func (void)

{

Char str [] = "Hello World"; // STR's memory is on the stack

Return str; // will result in errors

}

20, other suggestions for functions

2 Functions The function is single, do not design multi-purpose functions.

2 The scale of the function body is small, try to control within 50 lines of code.

2 Try to avoid the function with the "Memory" function. That is to say as little as possible, local variables are used, unless it is essential.

2 Not only to check the validity of the input parameters, but also check the validity of variables into the function in the function through other ways, such as global variables, file handles, etc.

22, copying the memory blocks that do not overlap

Void * Memcpy (void * pvto, const void * pvfrom, size_t size)

{Assert ((PVTO! = Null) && (pvfrom! = Null); // Using assertions

Byte * PBTO = (byte *) PVTO; / / Prevent the address of the PVTO

Byte * pbfrom = (byte *) PVFROM; / / Prevent the address of the PVFROM

While (size -> 0)

* PBTO = * PBFROM ;

Return PVTO;

}

21, use assertions

2 Use asserts to capture illegal situations that should not occur. Do not confuse the difference between illegal conditions and error conditions, the latter inevitably exist and must be processed. 2 At the entrance to the function, use assertion check parameters (legitimacy).

2 When writing a function, it is necessary to perform repeated exam, and ask: "What assumptions I plan?" Once the assumption is determined, it is necessary to check the assumption using the assertion.

22, quote and pointer comparison

Some rules referenced are as follows:

2 References must be initialized while being created (pointer can be initialized at any time).

2 No NULL reference, the reference must be associated with the legal storage unit (the pointer can be null).

2 Once the reference is initialized, the relationship of the reference cannot be changed (the pointer can change the object you refer to time).

The nature of "reference delivery" is like "pointer", and writing the way "value transfer". In fact, anything "pointer" that can be done can be done.

23, memory allocation method

2 Allocate from static storage area. There is already a hidden when there is program compilation, and there is existence of the entire running period of the program. For example, global variables, static variables.

2 Create on the stack. When performing a function, the storage unit of local variables within the function can be created on the stack, and the memory cells are automatically released at the end of the function. The stack memory allocation operation is within the command set of the processor, the efficiency is high, but the assigned memory capacity is limited.

2 Distribute from the heap, also known as dynamic memory allocation. The program applies for any number of memory with Malloc or New when running, and the programmer will release the memory with free or delete. Dynamic memory survival is determined by us, it is very flexible, but the problem is most.

24. Common memory errors and their countermeasures

1) The memory allocation is unsuccessful, but it uses it.

Workaround: Check the pointer to NULL before using the memory. If the pointer P is the parameter of the function, use Assert (P! = NULL) to check at the entry of the function. If you are using Malloc or New to apply for memory, you should use if (p = null) or if (p! = Null).

2), although memory allocation is successful, it is not initialized to reference it.

Solution: Don't forget to pay the initial value to the internal repository, even if you are zero value, you can't omit, don't be troublesome.

3) The memory allocation is successful and has been initialized, but the operation has crossed the boundary of the memory.

Solution: For example, the subscript "more 1" or "less 1" will occur, for example, when using an array.

4) Forgot to release memory, resulting in memory leakage.

Dynamic memory application and release must be paired, the number of malloc and free usage will be the same, otherwise there must be an error (New / Delete.).

5) Release memory but continue to use it.

Three cases:

(1) Object call relationship in the program is too complicated, and it is difficult to figure out whether an object has released memory. At this time, the data structure should be redesigned, fundamentally solve the chaotic situation of the object management.

(2) The RETURN statement of the function is wrong. Be careful not to return "pointer" or "reference" pointing to "Stack Ins), because the internal existence is automatically destroyed.

(3) After using Free or Delete releases the memory, the pointer is not set to NULL. Resulting in a "wild pointer".

25, memory usage rules

2 After using Malloc or New to apply for memory, you should immediately check if the pointer value is NULL. Prevent memory using the pointer value of NULL. 2 Don't forget to pay initial values ​​in the array and dynamic. Prevent memory that will not be initialized as the right value.

2 Avoid the subsidiaries of array or pointers, especially "more than 1" or "less 1" operation occurs.

2 Dynamic memory application and release must be paired to prevent memory leakage.

2 After the memory is released with free or delete, set the pointer to NULL to prevent "wild pointer".

转载请注明原文地址:https://www.9cbs.com/read-30564.html

New Post(0)