High quality c ++ Programming Guide Chapter 5-6-thanks to Lin Rui

Source: Internet
Author: User

Chapter 5 Constants

5. 1. Constant type

The C language uses # define to define constants (called macro constants ). In addition to # define, C ++ can also use const to define constants (called const constants ).

Const constants have data types, while macro constants do not. The compiler can perform type security checks on the former. The latter is only replaced by characters, and there is no type security check. Therefore, in C ++, only const constants are used instead of macro constants.

5. 2. Constant definition rules

[Rule 5-2-1] constants that need to be made public are placed in the header file, and constants that do not need to be made public are placed in the header of the definition file. For ease of management, constants of different modules can be stored in a public header file.

Constants in Class 5 and 3


Sometimes you want some constants to be valid only in the class. Because # The macro constant defined by define is global, it is assumed that it should be implemented by modifying the data member with Const. However, the const data member is a constant only within the lifetime of an object, but it is variable for the entire class. Because the class can create multiple objects, the values of const data members of different objects can be different. The const data member cannot be initialized in the header file, but can only be initialized in the const function.


How can we create constant constants in the entire class? It should be implemented using enumeration constants in the class. Enumerated constants do not occupy the storage space of objects. They are all assigned values during compilation. The disadvantage is that its implicit data type is an integer, its maximum value is limited, and it cannot represent a floating point number.

Chapter 6 function design

Function Design, how to design functions, parameters, return values, and implementations.

In C, function parameters and return values are transmitted through values and pointers. References are transferred in C ++. The nature passed by reference is like pointer passing, while the pattern passed is like value passing.

6. 1 parameter rules

[Rule 6-1-1] parameters must be completely written. Do not ignore parameter names only for parameter types. If no parameter is set, use void.

[Rule 6-1-2] The parameter name should be appropriate and the order should be reasonable. Generally, the target parameter should be placed first, and the source parameter should be placed later.

[Rule 6-1-3] If the parameter is a pointer and only used for input, add const before the type to prevent the pointer from being modified in the function body.

[Rule 6-1-4] If an input parameter transmits an object as a value, you should use the "const &" method to transfer the object. This saves the need for the Construction and Analysis of temporary objects, to improve efficiency.

[6-1-1] try to limit the number of parameters to less than 5.

[6-1-2] Do not use parameters with uncertain types and numbers. The C standard library function printf is a typical example of using uncertain parameters. Its prototype is: int
Printf (const char * Format [, argument]…) This type of function loses strict type security checks during compilation.

Rules for returning values 6 and 2

[Rule 6-2-1] Do not omit the type of the returned value. Because no type description function is added, C returns an integer by default. c ++ has a strict type check, so no such situation will occur. C ++ obfuscation when calling C.

[Rule 6-2-2] The function name and return value type cannot conflict in semantics. A typical violation of this rule is the c Standard library function getchar. The char type is obtained when the function name is used, but the int type is actually returned. Int
Getchar (void ).

[Rule 6-2-3] Do not mix normal values with error identifiers to return results. The normal value is obtained using the output parameter, and the error mark is returned using the return statement.

Why should the C standard library function designers declare getchar as a confusing int type? Normally, getchar does return a single character. However, if getchar encounters a file end identifier or a read error, it must return an EOF. To distinguish it from a normal character, we have to define the EOF as a negative number (usually-1 ). Therefore, the getchar function is int type.

In order to avoid the above situation, the normal value and the error mark should be separated. You can change getchar to bool getchar (char * C ).

[6-2-1] Sometimes the function does not need to return values, but to increase flexibility, such as supporting chained expressions, you can add return values.

For example, strcpy copies strsrc to the strdest parameter, and the return value of the function is strdest. This is not a single action multiple times, and the following flexibility is available: Char
STR [20]; int length = strlen (strcpy (STR, "Hello World "));

[6-2-2] If the return value of a function is an object, replacing "value transfer" with "reference transfer" in some cases can improve the efficiency. In some cases, you can only use "value transfer"; otherwise, errors may occur.

6. 3 internal implementation of functions

[Rule 6-3-1] checks the parameter validity at the "ENTRANCE" of the function body. Use assert correctly to prevent such errors.

[Rule 6-3-2] checks the correctness and efficiency of the Return Statement at the "exit" of the function body. Note:

Ø
The return statement cannot return "Pointer" or "Reference" pointing to "stack memory" because the function body is automatically destroyed when it ends.

Ø
If the returned function value is an object, the efficiency of the return statement should be considered. For example: Return string (str1 + str2); this is the syntax of a temporary object, indicating "Creating a temporary object and returning it ". Do not think it is equivalent to "first create a local object temp and return its results. Example: String
Temp (S1 + S2); Return temp; this code has three things. First, the temp object is created and initialized. Then, the copy constructor copies temp to the external storage unit that saves the returned value. Finally, temp is destroyed at the end of the function (the Destructor is called ). However, the process of "Creating a temporary object and returning it" is different. The Compiler directly creates and initializes the temporary object in an external storage unit, saving the cost of copying and analysis. Similarly, do not set the return
INT (x + y); int temp = x + y; return temp; because the internal data type variables do not have constructor and destructor, obviously, the "Syntax of temporary variables" does not provide much efficiency, but the program is simpler and easier to read.

6. 4. Other suggestions

[6-4-1] function functions should be single, and no multi-purpose functions should be designed. The scale should be small and should be within 50 rows as much as possible.

[6-4-2] do not use the "Memory" function. The static local variable of the function is the memory of the function. Use static local variables as few as possible.

[6-4-3] check not only the validity of input parameters, but also the validity of variables entering the function body through other channels, such as global variables and file handles.

6. 5 Use assertions


Programs are generally divided into debug and release versions. Assert is a macro that only works in the debug version. In order not to cause any difference between the debug and release versions of the program, assert should not produce any side effects. So assert is not a function, but a macro.

[Rule 6-5-1] Use assertions to capture illegal situations that should not occur. Do not confuse the differences between illegal situations and error situations. The latter must exist and be handled.

[Rule 6-5-2] At the function entrance, Use assertions to check the validity of parameters.

[Rule 6-5-3] When writing a function, you should repeat it and ask yourself, "What assumptions do I plan to make ?" Once the assumptions are determined, we need to use assertions to check the assumptions. ---------- Don't understand.

6. 6. Differences between references and pointers


Some referenced rules:

Ø
The reference must be initialized at the same time (the pointer can be initialized at any time ).

Ø
There cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ).

Ø
Once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time ).

The main function of the reference is to pass the parameters and return values of the function.

Value passing pointer passing reference passing

Void func1 (int x) void func1 (int * X) void func1 (Int & X)

{{{

X = x + 10; (* X) = (* x) + 10; X = x + 10;

}}}

Int n = 0; int n = 0; int n = 0;

Func1 (n); func1 (& N); func1 (N );

Cout <n; // n = 0; cout <n; // n = 10; cout <n; // n = 10;


It can be seen that the nature of "reference transfer" is like "pointer transfer", and the writing method is like "value transfer ". In fact, "Reference" can be used to do anything "Pointer". Why do we need to "Reference? The answer is "Use appropriate tools for proper work ". Pointers are powerful but dangerous.

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.