Generates a public-private key pair and configures the public key on the hpm server to enable hpm-cli.
+
Generates a public-private key pair and configures the public key on the hpm server, achieving password-free hpm-cli login for bundle publishing.
Generating third-party open source notice
diff --git a/docs-en/bundles/development-guidelines.md b/docs-en/bundles/development-guidelines.md
index c93e0d648cfaa6b0c3876a6d9086584ddaad4a0f..382f907feffa6179e7cc056c016d3b26e430a612 100755
--- a/docs-en/bundles/development-guidelines.md
+++ b/docs-en/bundles/development-guidelines.md
@@ -1,6 +1,6 @@
# Development Guidelines
-- **[Overview](overview.md)**
+- **[Overview](overview-0.md)**
- **[Preparations](preparations.md)**
diff --git a/docs-en/bundles/development-specifications.md b/docs-en/bundles/development-specifications.md
index af2eec9dbddd5f2d2665428c51bc65ee6c1a9f07..65c4502c9e05754a2d4a67e2122f2f00ad56cdc5 100755
--- a/docs-en/bundles/development-specifications.md
+++ b/docs-en/bundles/development-specifications.md
@@ -1,6 +1,6 @@
# Development Specifications
-- **[Overview](overview-0.md)**
+- **[Overview](overview.md)**
- **[Bundle Composition](bundle-composition.md)**
diff --git a/docs-en/bundles/overview-0.md b/docs-en/bundles/overview-0.md
index da961065816973053161acb949ae70ab185ae3fc..30513906bf6da223b799233c090b486c43d2c1df 100755
--- a/docs-en/bundles/overview-0.md
+++ b/docs-en/bundles/overview-0.md
@@ -1,34 +1,54 @@
-# Overview
-
-This document describes the basic concepts of a bundle and how to define it in compliance with specifications.
-
-## Definition
-
-OpenHarmony software is developed on a per-bundle basis. In terms of the operating system, all software running on OpenHarmony are bundles. Generally, bundles are classified into the following types based on their application scopes:
-
-- Board-level bundles: device hardware-specific bundles, such as **board**, **arch**, and **mcu**
-- System-level bundles: a set of bundles with independent features, such as the kernel, file system, and framework
-- Application-level bundles: applications that provide services to users, such as **wifi\_iot** and **ip\_camera**
-
-Bundles are designed for the reuse purpose. Any reusable modules can be defined as bundles. They are classified into the following types based on their forms:
-
-- Source code
-- Binary system
-- Code snippet
-- Distribution
-
-## Bundle Division Principles
-
-In principle, bundles should be grouped at a fine-grained granularity as much as possible to achieve maximum reuse. The following factors are taken into account regarding bundle division:
-
-- Independence: Bundles provide relatively independent features and can be independently compiled. Each of them is capable of providing its own APIs and services for external systems.
-- Coupling: If a bundle must depend on another bundle to provide services, they can be coupled to one bundle.
-- Correlation: If a group of bundles jointly implement a feature, and if other bundles never depend on them, the group of bundles can be combined into one bundle.
-
-## Bundle Dependency
-
-A bundle dependency can be mandatory or optional.
-
-- Mandatory dependency: If bundle A must depend on bundle B to implement a feature, that is, the APIs or services specific to bundle B must be invoked, then bundle B is defined as the mandatory dependency of bundle A.
-- Optional dependency: If either bundle C or bundle D is required for bundle A to implement a feature, and if bundle C and bundle D are interchangeable, then bundle C and bundle D are defined as optional dependencies of bundle A.
+# Overview
+
+This document describes how to develop OpenHarmony bundles and distributions, and how to create, develop, and build code, as well as burn and debug devices by using a command line tool.
+
+- A bundle usually maps onto a code repository, which is a code archive with the **bundle.json**, **README**, and **LICENSE** files.
+- A distribution consists of multiple bundles. Each distribution integrates various bundles of a comprehensive system, such as the driver, kernel, framework, and applications. These bundles can be used for device burning.
+
+**Table 1** Differences between a bundle and a distribution
+
+
+
Aspect
+
+
Bundle
+
+
Distribution
+
+
+
+
Application scenario
+
+
Feature-oriented
+
+
System-oriented
+
+
+
Content
+
+
Codes or a binary library for implementing features
+
+
List of dependent bundles as well as their compiling and building scripts
+
+
+
Integrity
+
+
A part of the operating system
+
+
An entire operating system
+
+
+
Compilation result
+
+
Bundles
+
+
System image
+
+
+
+
+
+**Figure 1** Composition of bundles and distributions
+
+
+![](figures/en-us_image_0000001054663940.png)
diff --git a/docs-en/bundles/overview.md b/docs-en/bundles/overview.md
index 30513906bf6da223b799233c090b486c43d2c1df..da961065816973053161acb949ae70ab185ae3fc 100755
--- a/docs-en/bundles/overview.md
+++ b/docs-en/bundles/overview.md
@@ -1,54 +1,34 @@
-# Overview
-
-This document describes how to develop OpenHarmony bundles and distributions, and how to create, develop, and build code, as well as burn and debug devices by using a command line tool.
-
-- A bundle usually maps onto a code repository, which is a code archive with the **bundle.json**, **README**, and **LICENSE** files.
-- A distribution consists of multiple bundles. Each distribution integrates various bundles of a comprehensive system, such as the driver, kernel, framework, and applications. These bundles can be used for device burning.
-
-**Table 1** Differences between a bundle and a distribution
-
-
-
Aspect
-
-
Bundle
-
-
Distribution
-
-
-
-
Application scenario
-
-
Feature-oriented
-
-
System-oriented
-
-
-
Content
-
-
Codes or a binary library for implementing features
-
-
List of dependent bundles as well as their compiling and building scripts
-
-
-
Integrity
-
-
A part of the operating system
-
-
An entire operating system
-
-
-
Compilation result
-
-
Bundles
-
-
System image
-
-
-
-
-
-**Figure 1** Composition of bundles and distributions
-
-
-![](figures/en-us_image_0000001054663940.png)
+# Overview
+
+This document describes the basic concepts of a bundle and how to define it in compliance with specifications.
+
+## Definition
+
+OpenHarmony software is developed on a per-bundle basis. In terms of the operating system, all software running on OpenHarmony are bundles. Generally, bundles are classified into the following types based on their application scopes:
+
+- Board-level bundles: device hardware-specific bundles, such as **board**, **arch**, and **mcu**
+- System-level bundles: a set of bundles with independent features, such as the kernel, file system, and framework
+- Application-level bundles: applications that provide services to users, such as **wifi\_iot** and **ip\_camera**
+
+Bundles are designed for the reuse purpose. Any reusable modules can be defined as bundles. They are classified into the following types based on their forms:
+
+- Source code
+- Binary system
+- Code snippet
+- Distribution
+
+## Bundle Division Principles
+
+In principle, bundles should be grouped at a fine-grained granularity as much as possible to achieve maximum reuse. The following factors are taken into account regarding bundle division:
+
+- Independence: Bundles provide relatively independent features and can be independently compiled. Each of them is capable of providing its own APIs and services for external systems.
+- Coupling: If a bundle must depend on another bundle to provide services, they can be coupled to one bundle.
+- Correlation: If a group of bundles jointly implement a feature, and if other bundles never depend on them, the group of bundles can be combined into one bundle.
+
+## Bundle Dependency
+
+A bundle dependency can be mandatory or optional.
+
+- Mandatory dependency: If bundle A must depend on bundle B to implement a feature, that is, the APIs or services specific to bundle B must be invoked, then bundle B is defined as the mandatory dependency of bundle A.
+- Optional dependency: If either bundle C or bundle D is required for bundle A to implement a feature, and if bundle C and bundle D are interchangeable, then bundle C and bundle D are defined as optional dependencies of bundle A.
diff --git a/docs-en/bundles/preparations.md b/docs-en/bundles/preparations.md
index b7471893cb72ec8e5d98a272ac4eea3c55ddeb88..3a0750c1411494e16c930c67f479b073138c4f52 100755
--- a/docs-en/bundles/preparations.md
+++ b/docs-en/bundles/preparations.md
@@ -54,15 +54,15 @@ login = https://hpm.harmonyos.com/hpm/auth/pk # Configure t
loginUser = {your-account} # Configure the account for HPM login, mandatory for publishing bundles.
shellPath = C:\WINDOWS\System32\cmd.exe # Configure the shell for running HPM commands.
globalRepo = C:\Users\yourname\.global # Configure the path for storing bundles that are installed globally.
-http_proxy = http://your-proxy-server:port # Configure the HTTP proxy.
-https_proxy = http://your-proxy-server:port # Configure the HTTPS proxy.
+http_proxy = http://your-proxy-server:port # Configure the HTTP proxy.
+https_proxy = http://your-proxy-server:port # Configure the HTTPS proxy.
```
For details about **hpm-cli** commands, see [HPM Commands](bundle-management.md#table10510164515371).
## Downloading OpenHarmony Code
-For details, see [Source Code Acquisition](../get-code/source-code-acquisition.md).
+For details, see .
## Installing Dependent Bundles
diff --git a/docs-en/contribute/OpenHarmony-JavaScript-coding-style-guide.md b/docs-en/contribute/OpenHarmony-JavaScript-coding-style-guide.md
old mode 100644
new mode 100755
diff --git a/docs-en/contribute/OpenHarmony-c-coding-style-guide.md b/docs-en/contribute/OpenHarmony-c-coding-style-guide.md
new file mode 100644
index 0000000000000000000000000000000000000000..6231319194293ad1bfdf9dfd6d51affe408889a1
--- /dev/null
+++ b/docs-en/contribute/OpenHarmony-c-coding-style-guide.md
@@ -0,0 +1,2116 @@
+# C Coding Style Guide
+
+## Purpose
+
+Rules are not perfect. Disabling useful features in specific situations may affect code implementation. However, the rules are formulated "to help most programmers to get more benefits". If a rule is found unhelpful or difficult to follow in team coding, please send your feedback to us so we can improve the rule accordingly. Before referring to this guide, you are expected to have the following basic capabilities for C rather than being a beginner who wants to learn about C.
+
+1. Understand the ISO standard of C.
+2. Be familiar with the basic features of C.
+3. Understand the standard library of C.
+
+## General Principles
+
+Code must meet the requirements for **readability**, **maintainability**, **security**, **reliability**, **testability**, **efficiency**, and **portability** while ensuring functionality correctness.
+
+## Conventions
+
+**Rule**: Conventions that must be followed during programming.
+**Suggestion**: Conventions that must be considered during programming.
+
+It is necessary to understand the reason for these conventions and to try and comply with them, no matter if they are rules or recommendations.
+
+## Exceptions
+
+The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for their existence.
+Exceptions destroy code consistency. Try to avoid them. Exceptions to 'Rules' should be very rare.
+
+The style consistency principle is preferred in the following case:
+**When you modify open source or third-party code. The existing code specifications prevail.**
+
+# 1 Naming
+
+Names include file, function, variable, type, and macro names.
+
+Naming is considered the most difficult and important thing in software development.
+The name of an identifier must be clear, well defined, and easy to understand, adapting to reading habit.
+
+The unified naming style is the most direct expression of the consistency principle.
+
+## General Conventions
+
+**CamelCase**
+Camel case is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation.
+This style has two alternatives depending on the case of the first letter: **UpperCamelCase and lowerCamelCase**
+
+### Rule 1.1 Name identifiers in camel case style.
+
+| Type| Naming Style
+|----------|----------
+| Function, struct, enumeration, union| UpperCamelCase
+| Variable, function parameter, macro parameter, struct body, union member| lowerCamelCase
+| Macro, constant, enumerated value, goto tag| All capitalized, separated with underscores (\_)
+
+Note:
+The `constant` in the above table refers to the variable of the basic data type, enumeration, and string type of the const modifier under the global scope, excluding array, struct and union.
+The `variable` in the above table refers to variables other than the constant definition, all using lowercase.
+
+### Rec 1.1 The larger the scope, the more accurate the name should be.
+
+C is different from C++. There is no namespace or class. Therefore, the names of identifiers in the global scope must not conflict with each other.
+Names of global functions, global variables, macros, types, and enumerations must be accurately described and unique in the global scope.
+
+Example:
+
+```c
+int GetCount(void); // Bad: inaccurate description.
+int GetActiveConnectCount(void); // Good
+```
+
+For accurate naming, a module prefix can be added if necessary.
+The module prefix and the naming body can be connected by following the CamelCase style.
+Example:
+
+```c
+int PrefixFuncName(void); // OK: CamelCase, with no prefix in the format, but prefix in the content.
+
+enum XxxMyEnum { // OK.
+ ...
+};
+```
+
+## File Naming
+
+### Rec 1.2 Use lowercase file names.
+
+File names naming are allowed only with lowercase letters, numbers, and underscores (\_).
+File names should be as short, accurate, and unambiguous as possible.
+The reason for using lowercase file names is that different systems process file names in different ways (for example, Microsoft DOS and Windows OS are not case sensitive, but Unix/Linux and Mac systems are by default).
+
+Good example:
+`dhcp_user_log.c`
+
+Bad examples:
+`dhcp_user-log.c`: It is not recommended you separate names with '-'.
+`dhcpuserlog.c`: The words are not separated, causing poor readability.
+
+## Function Naming
+
+Functions are named in UpperCamelCase style.
+
+### Rec 1.3 Name functions that comply with reading habits.
+
+The "verb + object" structure can be used for action related function names. For example:
+
+```c
+AddTableEntry() // OK
+DeleteUser() // OK
+GetUserInfo() // OK
+```
+
+An adjective or a prefix "is" can be used in a function returning a Boolean value. For example:
+
+```c
+DataReady() // OK
+IsRunning() // OK
+JobDone() // OK
+```
+
+Data or Getter function:
+
+```c
+TotalCount() // OK
+GetTotalCount() // OK
+```
+
+## Variable Naming
+
+Variables are named in the lowerCamelCase style. This includes global variables, local variables, parameters in the function declaration or definition as well as parameters in function-like macro.
+
+### Rule 1.2 Add the 'g\_' prefix to global variables. Do not add this prefix to static variables in a function.
+
+Global variables should be used as little as possible, and special attention should be paid to their use. Prefixes are used for visual prominence, prompting developers to be more careful about using global variables.
+The naming rule of global static variables is the same as that of global variables. The name of a static variable in a function is the same as that of a common local variable.
+
+```c
+int g_activeConnectCount;
+
+void Func(void)
+{
+ static int pktCount = 0;
+ ...
+}
+```
+
+Notes: The nature of a constant is also a global variable, but it does not apply to current rule if the naming style is all uppercase and connected by underline.
+
+### Rec 1.4 Keep local variables short and to the point.
+
+The name of a local variable should be short on the premise that meanings can be expressed through context.
+
+The following is an example:
+
+```c
+int Func(...)
+{
+ enum PowerBoardStatus powerBoardStatusOfSlot; // Not good: Long redundant local variable.
+ powerBoardStatusOfSlot = GetPowerBoardStatus(slot);
+ if (powerBoardStatusOfSlot == POWER_OFF) {
+ ...
+ }
+ ...
+}
+```
+
+Better writing style:
+
+```c
+int Func(...)
+{
+ enum PowerBoardStatus status; // Good: The status can be clearly expressed in context.
+ status = GetPowerBoardStatus(slot);
+ if (status == POWER_OFF) {
+ ...
+ }
+ ...
+}
+```
+
+Similarly, "tmp" can be used to address any type of temporary variable.
+A short variable name should be used with caution, but sometimes a single character variable is allowed, for example, a counter variable in a loop statement.
+
+```c
+int i;
+...
+for (i = 0; i < COUNTER_RANGE; i++) {
+ ...
+}
+```
+
+Or, variables in simple math functions:
+
+```c
+int Mul(int a, int b)
+{
+ return a * b;
+}
+```
+
+## Type Naming
+
+Types are named in the UpperCamelCase style.
+The type can be a structure, a union, or an enumeration.
+
+Example:
+
+```c
+struct MsgHead {
+ enum MsgType type;
+ int msgLen;
+ char *msgBuf;
+};
+
+union Packet {
+ struct SendPacket send;
+ struct RecvPacket recv;
+};
+
+enum BaseColor {
+ RED, // Note: The enumeration is in UpperCamelCase style while the enumerated values adopt the macro naming style.
+ GREEN,
+ BLUE
+};
+
+typedef int (*NodeCmpFunc)(struct Node *a, struct Node *b);
+```
+
+When you use typedef to set an alias for a struct, a union or an enum type, try to use anonymous type.
+If you need self-nesting pointers, you can add a 'tag' prefix or an underscore suffix.
+
+```c
+typedef struct { // Good: The anonymous struct is used because self-nesting is not required.
+ int a;
+ int b;
+} MyType; // Struct alias with UpperCamelCase.
+
+```c
+typedef struct tagNode { // Good: Add the 'tag' prefix or use 'Node_'.
+ struct tagNode *prev;
+ struct tagNode *next;
+} Node; // UpperCamelCase.
+```
+
+## Macros, Constants, and Enumeration Naming
+
+Macros and enumerated values are capitalized and are separated with underscores (\_).
+Constants are recommended to be capitalized and be separated with underscores (\_). Also, as global const variables, they can be named with global variable style.
+The constants here are defined as global const variables of basic data type, enumeration, and string type.
+
+Function-like macros, can be named the same way as functions, using the UpperCamelCase naming style.
+However, this approach makes the macros look the same as functions. It is confusing and needs special attention.
+
+Macro example:
+
+```c
+#define PI 3.14
+#define MAX(a, b) (((a) < (b)) ? (b) : (a))
+```
+
+```c
+#ifdef SOME_DEFINE
+void Bar(int);
+#define Foo(a) Bar(a) // The function-like macro is named as a function style.
+#else
+void Foo(int);
+#endif
+```
+
+Constant example:
+
+```c
+const int VERSION = 200; // OK.
+
+const enum Color DEFAULT_COLOR = BLUE; // OK.
+
+const char PATH_SEP = '/'; // OK.
+
+const char * const GREETINGS = "Hello, World!"; // OK.
+```
+
+Non-constant example:
+
+```c
+// Structure type does not meet the definition of constant.
+const struct MyType g_myData = { ... }; // OK: Name it in lowerCamelCase style.
+
+// Array type does not meet the definition of constant.
+const int g_xxxBaseValue[4] = { 1, 2, 4, 8 }; // OK: Name it in lowerCamelCase style.
+
+int Foo(...)
+{
+ // The scope does not meet the definition of constant.
+ const int bufSize = 100; // OK: Name it in lowerCamelCase style.
+ ...
+}
+```
+
+Enumeration example:
+
+```c
+// Note: The enumeration type name is in the UpperCamelCase style, while enumerated values are all capitalized and separated with underscores (_).
+enum BaseColor {
+ RED,
+ GREEN,
+ BLUE
+};
+```
+
+### Rec 1.5 Do not name temporary variables in function-like macros and pollute the external scope.
+
+First, **use function-like macros as little as possible.**
+
+When a function-like macro needs to define local variables, to avoid naming conflicts with local variables in external functions,
+
+an underline is a good solution. Example:
+
+```c
+#define SWAP_INT(a, b) do { \
+ int tmp_ = a; \
+ a = b; \
+ b = tmp_; \
+} while (0)
+```
+
+# 2 Formatting
+
+## Line Length
+
+### Rec 2.1 Ensure that each line is no more than 120 characters in length.
+
+The line width of the code should not be too long, otherwise it is not conducive to reading.
+The line length requirement indirectly guides developers in shortening function and variable names, reducing nesting, and improving readability.
+It is strongly recommended that the number of characters per line do not exceed **120** unless readability is significantly improved as a result and no information is hidden.
+While the resolution of modern monitors is very high, long lines will increase the difficulty of reading comprehension, which is against the principles of "clear" and "concise" defined in this document.
+
+The following scenarios should not be wrapped, and can be treated as exceptions:
+
+- Line breaks can cause strings truncated and hard to retrieved (grep), such as command lines or URLs. Codes or comments that contain these can be treated as exceptions appropriately.
+- '#include', '#error' statements are allowed to exceed the line width requirement, but you should try to avoid this.
+
+Example:
+
+```c
+#ifndef XXX_YYY_ZZZ
+#error Header aaaa/bbbb/cccc/abc.h must only be included after xxxx/yyyy/zzzz/xyz.h
+#endif
+```
+
+## Indentation
+
+### Rule 2.1 Use spaces to indent and indent four spaces at a time.
+
+Only spaces can be used for indentation. **4** spaces are indented each time. Do not use the Tab character to indent.
+Currently, almost all integrated development environments (IDEs) and code editors support automatically converting a Tab input to **4** spaces. Please set your code editor to support indentation with spaces, if it is not the default.
+
+## Braces
+
+### Rule 2.2 Use the K\&R indentation style.
+
+**K\&R style**
+While wrapping a line, the left brace of the function starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement.
+The right brace takes a single line, unless it is followed by the rest of the same statement, such as 'while' in the 'do' statement, or 'else'/'else if' of the 'if' statement, or a comma or semicolon.
+
+For example:
+
+```c
+struct MyType { // Good: Follow the statement to the end, and indent one space.
+ ...
+}; // Good: The right brace is followed by the semicolon.
+
+int Foo(int a)
+{ // Good: The left brace of the function starts a new line, and nothing else is placed on the line.
+ if (...) {
+ ...
+ } else { // Good: The 'else' statement follows the right brace.
+ ...
+ } // Good: The right brace takes a single line.
+}
+```
+
+## Function Declaration and Definition
+
+### Rule 2.3 The return type and function name of the function declaration and definition must be on the same line. The function parameter list must be aligned appropriately if it needs to be wrapped.
+
+When a function is declared and defined, the return value type of the function should be in the same line as the function name.
+
+When the function parameter list is wrapped, it should be aligned appropriately.
+The left parenthesis of a parameter list is always in the same line as the function name. The right parenthesis always follows the last parameter.
+
+The following is an example of line breaks:
+
+```c
+ReturnType FunctionName(ArgType paramName1, ArgType paramName2) // Good:All in one line
+{
+ ...
+}
+
+ReturnType VeryVeryVeryLongFunctionName(ArgType paramName1, // The line length cannot accommodate all parameters and thus a line break is required.
+ ArgType paramName2, // Good:Aligned with the previous line.
+ ArgType paramName3)
+{
+ ...
+}
+
+ReturnType LongFunctionName(ArgType paramName1, ArgType paramName2, // Subject to line length, a line break is required.
+ ArgType paramName3, ArgType paramName4, ArgType paramName5) // Good: After the line break, 4 spaces are used for indentation.
+{
+ ...
+}
+
+ReturnType ReallyReallyReallyReallyLongFunctionName( // The line length cannot accommodate the first parameter, and thus a line break is required.
+ ArgType paramName1, ArgType paramName2, ArgType paramName3) // Good: After the line break, 4 spaces are used for indentation.
+{
+ ...
+}
+```
+
+## Function Calls
+
+### Rule 2.4 The parameter list should be aligned appropriately when the parameter list requires a line break.
+
+When the function is called, if the function parameter list is wrapped, it should be aligned appropriately.
+The left parenthesis is always followed by a function name, and the right parenthesis always follows the last parameter.
+
+The following is an example of line breaks:
+
+```c
+ReturnType result = FunctionName(paramName1, paramName2); // Good:Function parameters are placed in one line.
+
+ReturnType result = FunctionName(paramName1,
+ paramName2, // Good:Aligned with the above parameters.
+ paramName3);
+
+ReturnType result = FunctionName(paramName1, paramName2,
+ paramName3, paramName4, paramName5); // Good:After the line break, 4 spaces are used for indentation.
+
+ReturnType result = VeryVeryVeryLongFunctionName( // The line length cannot accommodate the first parameter, and thus a line break is required.
+ paramName1, paramName2, paramName3); // After the line break, 4 spaces are used for indentation.
+```
+
+If the parameters in a function call are associated with each other, the parameters are grouped for better understanding, rather than strictly adhering to formatting requirements.
+
+```c
+// Good:The parameters in each line represent a group of data structures with a strong correlation. They are placed on one line for ease of understanding.
+int result = DealWithStructureLikeParams(left.x, left.y, // Indicates a group of parameters.
+ right.x, right.y); // Indicates another group of related parameters.
+```
+
+## Conditional Statements
+
+### Rule 2.5 Conditional statements must use braces.
+
+We require that all conditional statements use braces, even if there is only one statement.
+Reason:
+
+- Logic is intuitive and easy to read.
+- It is not easy to make mistakes when adding new code to the existing conditional statement.
+- Function-like macros without braces are used in conditional statements, can be error prone if braces do not surround the conditional statement.
+
+```c
+if (objectIsNotExist) { // Good: Braces are added to a single-line conditional statement.
+ return CreateNewObject();
+}
+```
+
+### Rule 2.6 Do not place 'if', 'else' and 'else if' in the same line.
+
+In a conditional statement, if there are multiple branches, they should be written in different lines.
+
+The correct format:
+
+```c
+if (someConditions) {
+ ...
+} else { // Good: The 'else' is in a different line of 'if'.
+ ...
+}
+```
+
+The following is a case that does not comply with the specifications:
+
+```c
+if (someConditions) { ... } else { ... } // Bad: They are in the same line.
+```
+
+## Loops
+
+### Rule 2.7 Use braces in loop statements.
+
+Similar to the condition expression, we require that the for and while loop conditional statements contain braces, even if there is only one loop.
+
+```c
+for (int i = 0; i < someRange; i++) { // Good: Braces are used.
+ DoSomething();
+}
+```
+
+```c
+while (condition) { } // Good: The while loop body is empty. And braces are used.
+```
+
+```c
+while (condition) {
+ continue; // Good: The continue keyword highlights the end of the empty loop. And braces are used.
+}
+```
+
+Bad example:
+
+```c
+for (int i = 0; i < someRange; i++)
+ DoSomething(); // Bad: Braces should be added.
+```
+
+```c
+while (condition); // Bad: Using semicolons will make people misunderstand which code is a part of the while statement.
+```
+
+## Switch Statements
+
+### Rule 2.8 Indent the case or default statement in a switch statement block.
+
+The indentation style of the switch statement is as follows:
+
+```c
+switch (var) {
+ case 0: // Good: Indented
+ DoSomething1(); // Good: Indented
+ break;
+ case 1: { // Good: Braces are added.
+ DoSomething2();
+ break;
+ }
+ default:
+ break;
+}
+```
+
+```c
+switch (var) {
+case 0: // Bad: 'case' not indented
+ DoSomething();
+ break;
+default: // Bad: 'default' not indented
+ break;
+}
+```
+
+## Expressions
+
+### Rec 2.2 Keep a consistent expression line break style and ensure that operators are placed at the end of the line.
+
+A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped at an operator of a lower priority or a hyphen, and the operator or hyphen is placed at the end of the line.
+The operator and hyphen are placed at the end of the line, indicating that the operation is to be continued.
+
+Example:
+
+```c
+// Pretend that the following first line does not meet the line length requirement.
+if ((currentValue > MIN) && // Good: After the line break, the Boolean operator is placed at the end of the line.
+ (currentValue < MAX)) {
+ DoSomething();
+ ...
+}
+
+int result = reallyReallyLongVariableName1 + // Good: The plus sign is placed at the end of the line.
+ reallyReallyLongVariableName2;
+```
+
+After an expression is wrapped, ensure that the lines are properly aligned or indented by 4 spaces. See the following example.
+
+```c
+int sum = longVaribleName1 + longVaribleName2 + longVaribleName3 +
+ longVaribleName4 + longVaribleName5 + longVaribleName6; // OK: indented with 4 spaces
+
+int sum = longVaribleName1 + longVaribleName2 + longVaribleName3 +
+ longVaribleName4 + longVaribleName5 + longVaribleName6; // OK: aligned
+```
+
+## Variable Assignment
+
+### Rule 2.9 Multiple variable definitions and assignment statements cannot be written on one line.
+
+It is best to have only one variable initialization statement on each line. It is easier to read and understand.
+
+```c
+int maxCount = 10;
+bool isCompleted = false;
+```
+
+The following is an example that does not comply with the specifications:
+
+```c
+int maxCount = 10; bool isCompleted = false; // Bad: Multiple initialization statements are placed on the same line.
+int x, y = 0; // Bad: Variable definitions need to be placed on different lines. Each definition occupies one line.
+
+int pointX;
+int pointY;
+...
+pointX = 1; pointY = 2; // Bad: Multiple variable assignment statements are placed on the same line.
+```
+
+Exception:
+If multiple variables with strong correlation are defined and do not need to be initialized, you can define the variables in a line to reduce repeated information so that the code is more compact.
+
+```c
+int i, j; // Good: Multiple variables that are defined and do not need to be initialized immediately can be written in one line.
+for (i = 0; i < row; i++) {
+ for (j = 0; j < col; j++) {
+ ...
+ }
+}
+```
+
+## Initialization
+
+Initialization is applicable to structs, unions, and arrays.
+
+### Rule 2.10 Indent when initiating a new line, or make a reasonable alignment.
+
+When a structure or array is initialized, if a line break is made, ensure that the line is indented with 4 spaces.
+From the readability point of view, make a reasonable alignment.
+
+```c
+// Good: No line break for a short line.
+int arr[4] = { 1, 2, 3, 4 };
+
+// Good: A line break here makes the readability better.
+const int rank[] = {
+ 16, 16, 16, 16, 32, 32, 32, 32,
+ 64, 64, 64, 64, 32, 32, 32, 32
+};
+```
+
+For complex data, the initialization should be clear and compact.
+Refer to the following format:
+
+```c
+int a[][4] = {
+ { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, // OK.
+ { 3, 2, 3, 4 }, { 4, 2, 3, 4 }
+};
+
+int b[][8] = {
+ { 1, 2, 3, 4, 5, 6, 7, 8 }, // OK.
+ { 2, 2, 3, 4, 5, 6, 7, 8 }
+};
+```
+
+```c
+int c[][8] = {
+ {
+ 1, 2, 3, 4, 5, 6, 7, 8 // OK.
+ }, {
+ 2, 2, 3, 4, 5, 6, 7, 8
+ }
+};
+```
+
+Note:
+
+- If the left brace is placed at the end of the line, the corresponding right brace shoud be placed into a new line.
+- If the left brace is followed by the content, the corresponding right brace should also follow the content.
+
+### Rule 2.11 When struct and union members are initialized, each member is initialized on a separate line.
+
+The C99 standard supports the initialization of the struct and union members in their definition. This is called the designated initializer. If initialization is performed in this way, each member is initialized in a separate line.
+
+```c
+struct Date {
+ int year;
+ int month;
+ int day;
+};
+
+struct Date date = { // Good: When the designated initializer is used, each member is initialized on a separate line.
+ .year = 2000,
+ .month = 1,
+ .day = 1
+};
+```
+
+## Pointers
+
+### Rec 2.3 The pointer type asterisk "\*" follows the variable name or the type. Do not leave spaces on both sides and always use at least one space.
+
+When you declare or define a pointer variable or return a pointer type function, "\*" can be placed on the left or right, adhering to the type or name. Do not leave spaces on both sides. And do not leave out spaces altogether.
+
+```c
+int *p1; // OK.
+int* p2; // OK.
+
+int*p3; // Bad: No spaces.
+int * p4; // Bad: Spaces on both sides.
+```
+
+Choose a style and stay consistent.
+
+When using style that "\*" follows type, avoid declaring multiple variables with pointer in a line.
+
+```c
+int* a, b; // Bad: It is easy to misinterpret b as a pointer.
+```
+
+When using style that "\*" follows variable, there may be situations that cannot be followed.
+Do not follow when it cannot. Style consistency first.
+
+```c
+char * const VERSION = "V100"; // OK.
+int Foo(const char * restrict p); // OK.
+```
+
+"\*" never follows 'const' or 'restrict' keywords anytime.
+
+## Compilation Preprocessing
+
+### Rule 2.12 The number sign (#) must be placed at the beginning of a line for compilation preprocessing and can be indented in nested compilation preprocessing.
+
+The number sign (#) must be placed at the beginning of a line for compilation preprocessing, even if the code is embedded in the function body.
+
+```c
+#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) // Good: "#" is at the beginning of the line.
+#define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: "#" is at the beginning of the line.
+#else
+#define ATOMIC_X86_HAS_CMPXCHG16B 0
+#endif
+
+int FunctionName(void)
+{
+ if (someThingError) {
+ ...
+#ifdef HAS_SYSLOG // Good: "#" is at the beginning of the line even though it's in a function body.
+ WriteToSysLog();
+#else
+ WriteToFileLog();
+#endif
+ }
+}
+```
+
+Nested preprocessing statements starting with "#" can be indented and aligned based on indentation requirements to different layers.
+
+```c
+#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
+ #define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: Statements are layered, facilitating reading.
+#else
+ #define ATOMIC_X86_HAS_CMPXCHG16B 0
+#endif
+```
+
+## Whitespace
+
+### Rule 2.13 Ensure that horizontal whitespace is used to highlight keywords, important information and avoid unnecessary whitespace.
+
+Horizontal spaces should be used to highlight keywords and important information. Do not add spaces at the end of each line of code. The general rules are as follows:
+
+- Add spaces after keywords such as if, switch, case, do, while, and for.
+- Do not add spaces after the left parenthesis or before the right parenthesis.
+- Add a space before and after each binary operator (= + - \< > \* / % \| \& \^ \<= >= == !=).
+- Do not add a space after any unary operator (\& \* + - ~!).
+- A space is required before and after each ternary operator (? :).
+- Add spaces before and after the colon of bit field description.
+- There is no space between ++/-- and variables.
+- There is no space before and after the struct member operator (. ->).
+- Adding or not adding spaces inside the brace must be consistent.
+- Do not add spaces before commas, semicolons, colons (without the colon in the ternary operator or the bit field description); Add spaces after them.
+- There is no space between the parentheses of the function parameter list and the function name.
+- There is no space between the parenthesis of the type cast and the object being converted.
+- There is no space between the square bracket of the array and the array name.
+- Spaces at the end of the line can be omitted.
+
+For spaces inside the braces, the following are **recommended**:
+
+- In general, spaces should be added after the left brace or before the right brace.
+- For empty, or a single identifier, or a single literal constant, spaces are not required. Such as: '{}', '{0}', '{NULL}', '{"hi"}'.
+- Spaces between consecutively nested multiple parentheses, spaces are not required. Such as: '{{0}}', '{{ 1, 2 }}'. Bad example: '{ 0, {1}}'. It is not a continuous nested scene, and the spaces inside the outermost braces are inconsistent.
+
+In normal cases:
+
+```c
+int i = 0; // Good: When the variable is initialized, there should be spaces before and after the =. Do not leave a space before the semicolon.
+int buf[BUF_SIZE] = {0}; // Good: During array initialization, spaces in curly braces are optional.
+int arr[] = { 10, 20 }; // Good: A space is added before and after the brace.
+```
+
+Function definition and call:
+
+```c
+int result = Foo(arg1,arg2);
+ ^ // Bad: There should be a space after the comma.
+
+int result = Foo( arg1, arg2 );
+ ^ ^ // Bad: No space should be added to either side in the parentheses.
+```
+
+Pointer and address-of operator:
+
+```c
+x = *p; // Good: There is no space between the operator * and the pointer p.
+p = &x; // Good: There is no space between the operator & and the variable x.
+x = r.y; // Good: When a member variable is accessed through the operator (.), no space is added.
+x = r->y; // Good: When a member variable is accessed through the operator (.), no space is added.
+```
+
+Operator:
+
+```c
+x = 0; // Good: A space must be added before and after the assignment operator (=).
+x = -5; // Good: Do not add spaces before the minus sign (-) and the number.
+++x; // Good: Do not add spaces before the minus sign (-) and the number.
+x--;
+
+if (x && !y) // Good: A space must be added before and after the Boolean operator. Do not leave spaces between the ! operator and variables.
+v = w * x + y / z; // Good: A space must be added before and after binary operators.
+v = w * (x + z); // Good: No space is required before and after the expression in the parentheses.
+```
+
+Loops and conditional statements:
+
+```c
+if (condition) { // Good: A space is added between the if keyword and the parenthesis and no space is added before or after the conditional statement inside the parentheses.
+ ...
+} else { // Good: A space is added between the else keyword and the curly brace.
+ ...
+}
+
+while (condition) {} // Good: A space is added between the while keyword and the parenthesis. No space is added before or after the conditional statement inside the parentheses.
+
+for (int i = 0; i < someRange; ++i) { // Good: A space is added between the for keyword and the parenthesis, and after the semicolons (;).
+ ...
+}
+
+switch (var) { // Good: A space is added after the switch keyword.
+ case 0: // Good: No space is added between the case conditional statement and the colon.
+ ...
+ break;
+ ...
+ default:
+ ...
+ break;
+}
+```
+
+Note: Current integrated development environments (IDEs) and code editors can be set to automatically delete spaces at the end of a line. Please configure your editor as such.
+
+### Rec 2.4 Arrange blank lines reasonably keep the code compact.
+
+Reduce unnecessary blank lines so that more code can be displayed for easy reading. The following rules are recommended:
+
+- Make a reasonable arrangement of blank lines according to the degree of relevance of neighboring content.
+- Do not put two or more consecutive blank lines inside a function, a type definition, a macro, or an initialization expression.
+- Do not use **three** or more consecutive blank lines.
+- Do not add blank lines at the start and end of a code block defined by braces.
+
+```c
+ret = DoSomething();
+
+if (ret != OK) { // Bad: Return value judgment should follow the function call.
+ return -1;
+}
+```
+
+```c
+int Foo(void)
+{
+ ...
+}
+
+
+
+int Bar(void) // Bad: Use no more than two continuous blank lines.
+{
+ ...
+}
+```
+
+```c
+int Foo(void)
+{
+
+ DoSomething(); // Bad: The blank lines above and below are unnecessary.
+ ...
+
+}
+```
+
+# 3 Comments
+
+Generally, clear architecture and good symbol naming are recommended to improve code readability, and comments are provided only when necessary.
+Comments help readers quickly understand code. Therefore, **comments should be provided when necessary** for the sake of readers.
+
+The comments must be concise, clear, and unambiguous, ensuring that the information is complete and not redundant.
+
+**Comments are as important as code.**
+When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the function and intention of code, rather than repeating code.
+When modifying the code, ensure that the comments are consistent. It is impolite to only modify code and not update the comments. It destroys the consistency between code and comments, and may confuse or even mislead readers.
+
+Comment code in fluent English.
+
+## Comment Style
+
+In C code, both `/*` `*/` and `//` can be used.
+Comments can be classified into different types depending on purpose and position, such as file header comments, function header comments, and general comments.
+Comments of the same type must keep a consistent style.
+
+Note: The sample code used in this article sees extensive use of the '//' post-comment. This is only to aid understanding, and does not mean that this comment style is better.
+
+## File Header Comments
+
+### Rule 3.1 File header comments must contain the copyright license.
+
+/\*
+
+* Copyright (c) 2020 Huawei Device Co., Ltd.
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. \*/
+
+## Function Header Comments
+
+### Rule 3.2 Empty function header comments with no content are forbidden.
+
+Not all functions need function header comments.
+Function header comments must be added for any information that cannot be expressed just with function prototype.
+
+Function header comments are placed above the function declaration or definition.
+Select and use one of the following styles:
+**Use '//' to start the function header.**
+
+```c
+// Single-line function header
+int Func1(void);
+
+// Multi-line function header
+// Second line
+int Func2(void);
+```
+
+**Use '/\*' '\*/' to start the function header.**
+
+```c
+/* Single-line function header */
+int Func1(void);
+
+/*
+ * Single-line or multi-line function header
+ * Second line
+ */
+int Func2(void);
+```
+
+Use function names to describe functions, and only add function header comments if necessary.
+Do not write useless or redundant function headers. Do not write empty function headers with no content.
+
+The function header comment content is **optional** any may include the following: function description, return value, performance constraint, usage, memory convention, algorithm implementation, and reentering requirements.
+In the function interface declaration in the external header file of the module, the function header comment should clearly describe important and useful information.
+
+Example:
+
+```c
+/*
+ * The number of written bytes is returned. If -1 is returned, the write operation fails.
+ * Note that, the memory buffer is released by the caller.
+ */
+int WriteString(char *buf, int len);
+```
+
+Bad example:
+
+```c
+/*
+ * Function name: WriteString
+ * Function: Write a character string.
+ * Parameter:
+ * Return value:
+ */
+int WriteString(char *buf, int len);
+```
+
+Problems in the preceding example are as follows:
+
+- The 'Parameter' and 'Return value' headings have no content.
+- The function name has redundant information.
+- The most important thing, the notice to release the buffer, is not clearly stated.
+
+## Code Comments
+
+### Rule 3.3 Code comments are placed above or to the right of the corresponding code.
+
+### Rule 3.4 There must be a space between the comment character and the comment content. At least one space is required between the comment and code if the comment is placed to the right of code.
+
+Comments placed above code should be indented to the same level as the code.
+Select and use one of the following styles:
+**Use '//' to start the comment.**
+
+```c
+// Single-line comment
+DoSomething();
+
+// Multi-line comment
+// Second line
+DoSomething();
+```
+
+**Use '/\*' '\*/' to start the comment.**
+
+```c
+/*Single-line comment */
+DoSomething();
+
+/*
+ * Single-/Multi-line comment
+ * Second line
+ */
+DoSomething();
+```
+
+Leave at least one space between the code and the comment on the right. No more than four spaces is recommended.
+You can use the extended Tab key to indent 1-4 spaces.
+
+Select and use one of the following styles:
+
+```c
+int foo = 100; // Comment on the right
+int bar = 200; /* Comment on the right */
+```
+
+It is more appealing sometimes when the comment is placed to the right of code and the comments and code are aligned vertically.
+After the alignment, ensure that the comment is 1–4 spaces separated from the closest code line on the left.
+Example:
+
+```c
+#define A_CONST 100 /* Related comments of the same type can be aligned vertically. */
+#define ANOTHER_CONST 200 /* Leave spaces after code to align comments vertically. */
+```
+
+If the comment on the right exceeds the permitted line length, the comment can be placed above the code.
+
+### Rule 3.5 Delete unused code segments. Do not comment them out.
+
+Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects.
+The correct method is to delete unnecessary code. If necessary, consider porting or rewriting the code.
+
+Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /\* \*/, //, #if 0, #ifdef NEVER\_DEFINED, and so on.
+
+### Rec 3.1 No TODO, TBD, or FIXME comment is allowed in code delivered to a customer.
+
+TODO and TBD comments are used to describe required improvements and supplements.
+FIXME comments are used to describe defects that need fixing.
+They should have a standardized style, which facilitates text search. For example:
+
+```c
+// TODO(): Supplement to XX
+// FIXME: XX defect
+```
+
+During version development, this type of comments can be used for highlighting, and must be processed and deleted before delivery.
+
+### Rec 3.2 If 'break' or 'return' is not added to the end of the case statement block (fall-through), comments must be provided.
+
+Sometimes, the same thing is needed for multiple case tags. When a case statement ends without 'break' or 'return', the statement in the next case tag will be executed. This is called "fall-through".
+In this case, you need to add comments for the "fall-through" to clearly describe your intention.
+
+For example, explicitly specify the "fall-through”:
+
+```c
+switch (var) {
+ case 0:
+ DoSomething();
+ /* fall-through */
+ case 1:
+ DoSomeOtherThing();
+ ...
+ break;
+ default:
+ DoNothing();
+ break;
+}
+```
+
+If the case statement is empty, the comment explaining the "fall-through" can be omitted.
+
+```c
+switch (var) {
+ case 0:
+ case 1:
+ DoSomething();
+ break;
+ default:
+ DoNothing();
+ break;
+}
+```
+
+# 4 Header Files
+
+**For the C language, the design of the header file reflects most of the system design.**
+The correct use of the header file makes code more readable, reduces file size, and speeds up compilation and build performance.
+
+This chapter summarizes some methods from the perspective of programming specifications to help you properly plan header files.
+
+## Header File Responsibility
+
+A header file is an external interface of a module or file.
+The interface declaration for most functions (except inline functions), is more suitable in the header file, than as interface implementations.
+Header responsibility should be simple. A complex header file will make dependencies complex and cause long compilation times.
+
+### Rec 4.1 Each .c file must have a corresponding .h file, which is used to declare the interfaces that need to be disclosed externally.
+
+Generally, each .c file has a corresponding .h file (Not necessarily the same name.), which is used to store the function declarations, macro definitions, and type definitions that are to be exposed externally.
+If a .c file does not need to open any interface externally, it should not exist.
+
+Exception: the entry point of the program (for example, the file where the main function is located), unit test code, and dynamic library code.
+
+Example:
+foo.h content
+
+```c
+#ifndef FOO_H
+#define FOO_H
+
+int Foo(void); // Good: Declare an external interface in the header file.
+
+#endif
+```
+
+foo.c content
+
+```c
+static void Bar(void); // Good: The declaration of the internal function is placed in the header of the .c file, declaring its static scope.
+
+void Foo(void)
+{
+ Bar();
+}
+
+static void Bar(void)
+{
+ // Do something;
+}
+```
+
+Internally used functions declarations, macros, enumerations, structures, and others should not be placed in header files.
+
+In some products, one .c file corresponds to two .h files. One is used to store external public interfaces, and the other is used to store definitions and declarations among others for internal use to limit the number of code lines in the .c file.
+This style is not recommended. It is used only because the .c file is too large. It should be split into another file instead.
+In addition, if private definitions and declarations are placed in independent header files, they technically cannot avoid inclusion.
+
+This rule, in turn, is not necessarily correct. For example:
+Some simple header files, such as the command ID definition header file, do not need to have the corresponding .c file.
+If a set of interface protocols has multiple instances and the interface is fixed, one .h file can have multiple .c files.
+
+### Rec 4.2 Use .h as the extension of the header file, rather than other unconventional extensions, for example, .inc.
+
+Some products use .inc as the header file name extension, which does not comply with the C language. A header file using .inc as the file name extension usually indicates a private header file. However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. This document does not recommend that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1).
+
+## Header File Dependency
+
+The header file contains a dependency, and the dependency should be stable.
+Generally, an unstable module depends on a stable module. When the unstable module changes, the build of the stable module is not affected.
+
+Dependency direction is as follows: Products depend on the platform, and the platform depends on the standard library.
+
+In addition to unstable modules depending on stable modules, each module depends on the interface. In this way, in case of any internal implementation changes to one module, users do not need to recompile another module.
+This assumes that the interface itself is the most stable.
+
+### Rule 4.1 Forbid cyclic dependency of header files.
+
+Cyclic dependency (also known as a circular dependency) of header files means that a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any header file is modified, all code containing a.h, b.h, and c.h needs to be recompiled.
+For a unidirectional dependency: a.h contains b.h, b.h contains c.h, and c.h does not contain any header file, modifying a.h does not mean a need to recompile the source code for b.h or c.h.
+
+The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization.
+
+### Rule 4.2 The header file must have the internal #include protection character (#define protection).
+
+To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once.
+
+When defining a protection character, comply with the following rules:
+
+- The protection character uses a unique name. It is recommended to consider the file path and name below the top layer of the project code tree.
+- Do not place code or comments before or after the protected part, except for file header comments.
+
+Assume that the path to timer.h of the timer module is `timer/include/timer.h`. If the protection character resembles 'TIME\_H', it is not unique. Add a path, for example:
+
+```c
+#ifndef TIMER_INCLUDE_TIMER_H
+#define TIMER_INCLUDE_TIMER_H
+
+...
+
+#endif
+```
+
+### Rule 4.3 Do not reference external function interfaces and variables by using declaration.
+
+You can use the interfaces provided by other modules or files only by using header files.
+Using external function interfaces and variables with an extern declaration may cause inconsistency between declarations and definitions when external interfaces are changed.
+In addition, this kind of implicit dependency may cause architecture corruption.
+
+Cases that do not comply with specifications:
+a.c content
+
+```c
+extern int Foo(void); // Bad: Reference external functions by using the extern declaration.
+void Bar(void)
+{
+ int i = Foo(); // Here, the external interface Foo is used.
+ ...
+}
+```
+
+It should be changed to:
+a.c content
+
+```c
+#include "b.h" // Good: Use the interface providing the interface.
+void Bar(void)
+{
+ int i = Foo();
+ ...
+}
+```
+
+b.h content
+
+```c
+int Foo(void);
+```
+
+b.c content
+
+```c
+int Foo(void)
+{
+ // Do something
+}
+```
+
+In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used.
+For example:
+When performing unit testing on an internal function, you can use the extern declaration to reference the tested function.
+When a function needs to be stubbed or patched, the function can be declared using extern.
+
+### Rule 4.4 Do not include header files in extern "C".
+
+If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the nesting of extern "C". If there are too many nested layers, compilation errors may occur.
+
+extern "C" usually occurs in mixed programming using both C and C++. If the extern "C" includes a header file, the original intent behind the header file may be hindered. For example, when the linkage specifications are modified incorrectly.
+
+For example, assume that there are two header files a.h and b.h.
+a.h content
+
+```c
+...
+#ifdef __cplusplus
+void Foo(int);
+#define A(value) Foo(value)
+#else
+void A(int)
+#endif
+```
+
+b.h content
+
+```c
+...
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "a.h"
+void B(void);
+
+#ifdef __cplusplus
+}
+#endif
+```
+
+Using the C++ preprocessor to expand b.h, the following information is displayed:
+
+```c
+extern "C" {
+ void Foo(int);
+ void B(void);
+}
+```
+
+In the a.h file, the function Foo is intended to be a C++ free function following the C++ specifications. However, in the b.h file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of function Foo is changed incorrectly.
+
+Exception: In the C++ compilation environment, if you want to reference a header file written in pure C, a non-intrusive approach is to exclude the C header file from `extern "C"`.
+
+# 5 Functions
+
+Functions help avoid repeated code and increase reusability. In addition, functions act to layer code and reduce code complexity, hiding implementation details, making programs more modular, and facilitating reading and maintenance.
+
+The function should be concise and short.
+One function completes only one thing.
+
+## Function Design
+
+Writing clean functions and organizing code effectively is the essence of good function design. The code should be simple and not conceal the designer's intention, using clean abstractions and straightforward control statements to organize the function naturally.
+
+### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (not including blank lines and comments).
+
+A function should fit on one screen, (be no longer than 50 lines), do only one thing, and do it well.
+
+Large functions are often caused by the fulfillment of more than one purpose by the function, or over complication when parts could be abstracted.
+
+Exception:
+Considering the code's aggregation and functionality, some functions may exceed 50 lines, but only if the code is readable and concise.
+These exceptions should be minimal, such as specific algorithm processing.
+
+Even if a large function works well in the moment, once someone modifies it, new problems may occur. It may even cause bugs that are difficult to discover.
+It is recommended that you split it into several simpler and easier to manage functions, facilitating reading and modification of code.
+
+### Rule 5.2 Avoid nesting a code block more than four times within a function.
+
+The nested code block depth of a function refers to the layered depth of a code control block (created by statements such as: if, for, while, and switch).
+Each layer of nesting increases the brain power required to read the code, because you need to maintain a "stack" in your mind comprised of each conditional statement, loop, and so on.
+Code should be broken down functionally to prevent the reader from remembering too much context at a time.
+
+Using `guardian statements`, (a short conditional return), can effectively reduce the nesting layers of if statements. For example:
+The original code nesting level is 3:
+
+```c
+int Foo(...)
+{
+ if (received) {
+ type = GetMsgType(msg);
+ if (type != UNKNOWN) {
+ return DealMsg(...);
+ }
+ }
+ return -1;
+}
+```
+
+Refactored code using the `guardian statement`, the nesting level is 2:
+
+```c
+int Foo(...)
+{
+ if (!received) { // Good: Use the 'guardian statement'.
+ return -1;
+ }
+
+ type = GetMsgType(msg);
+ if (type == UNKNOWN) {
+ return -1;
+ }
+
+ return DealMsg(..);
+}
+```
+
+Exception:
+Considering the code's aggregation and functionality, some functions may exceed 4 times nested, but only if the code is readable and concise.
+These exceptions should be rare.
+
+### Rec 5.1 Process all returned error codes.
+
+A function (in a standard library, a third-party library, or a user-defined function) must be able to indicate errors. This can be done by using error tags, special return data, or other means. No matter when a function provides such a mechanism, the caller should immediately check the error indication after the function returns.
+
+Example:
+
+```c
+char fileHead[128];
+ReadFileHead(fileName, fileHead, sizeof(fileHead)); // Bad: The returned value is not checked.
+
+DealWithFileHead(fileHead, sizeof(fileHead)); // The 'fileHead' is possibly invalid.
+```
+
+The correct format is as follows:
+
+```c
+char fileHead[128];
+ret = ReadFileHead(fileName, fileHead, sizeof(fileHead));
+if (ret != OK) { // Good: Ensure that the 'fileHead' is written.
+ return ERROR;
+}
+
+DealWithFileHead(fileHead, sizeof(fileHead)); // Process the file header.
+```
+
+Note that when the return value of a function is ignored and instead void is returned frequently, consider whether the return value of the function is designed reasonably.
+Only if the caller of a function really doesn't need a return value, should you design the function to return `void`.
+
+## Function Parameters
+
+### Rec 5.2 Use the return value instead of the output parameter when designing a function.
+
+Using return values rather than output parameters improves readability and usually provides the same or better performance.
+
+Readability can be improved by naming functions such as GetXxx, FindXxx, or directly using a single noun, to directly return the corresponding object.
+
+### Rec 5.3 Use strongly typed parameters and avoid using void\*
+
+While different languages have their own views on strong typing and weak typing, it is generally believed that C/C++ is a strongly typed language. Since we use such a strongly typed language, we should keep this style.
+The advantage of this strongly typed style is to prevent evasive errors by catching errors at the compilation stage.
+
+Strong types help the compiler find more errors for us. Pay attention to the usage of the `FooListAddNode` function in the following code:
+
+```c
+struct FooNode {
+ struct List link;
+ int foo;
+};
+
+struct BarNode {
+ struct List link;
+ int bar;
+}
+
+void FooListAddNode(void *node) // Bad: Here, the void * type is used to pass parameters.
+{
+ FooNode *foo = (FooNode *)node;
+ ListAppend(&g_fooList, &foo->link);
+}
+
+void MakeTheList(...)
+{
+ FooNode *foo;
+ BarNode *bar;
+ ...
+
+ FooListAddNode(bar); // Wrong: In this example, the foo parameter was supposed to be passed, but the bar parameter is incorrectly passed instead. No error is reported immediately and issues may occur as a result.
+}
+
+```
+
+The preceding problems may be difficult to expose and are more destructive than compiler errors.
+If the parameter type of `FooListAddNode` is specified clearly, instead of with the `void *` type, the preceding problem can be detected during compilation.
+
+```c
+void FooListAddNode(FooNode *foo)
+{
+ ListAppend(&g_fooList, &foo->link);
+}
+```
+
+Exception: For some generic interfaces, you can use the input parameter `void *` to pass different types of pointers.
+
+### It is the caller's responsibility to check the validity of internal function parameters of a module.
+
+Validity checks must be performed on data received from external modules to protect programs against illegal input.
+When calling internal functions, by default, the caller is responsible for ensuring the validity of any returned data. If the callee takes responsibility for checking data validity, checks may be performed multiple times and redundant code is generated. This is not concise.
+
+The caller ensures the validity of any received data. This type of contractual programming can make logic simpler and code more readable.
+Example:
+
+```c
+int SomeProc(...)
+{
+ int data;
+
+ bool dataOK = GetData(&data); // Get data.
+ if (!dataOK) { // Check the result of the previous step ensuring data validity.
+ return -1;
+ }
+
+ DealWithData(data); // Call the data processing function.
+ ...
+}
+
+void DealWithData(int data)
+{
+ if (data < MIN || data > MAX) { // Bad: The caller has already ensured the validity of the data.
+ return;
+ }
+
+ ...
+}
+```
+
+### Rec 5.5 The pointer argument of a function should be declared as 'const' if it is not used to modify the pointed object.
+
+The const pointer argument, which restricts the function from modifying the object through the pointer, makes code stronger and safer.
+
+Example: In the example of the strncmp in the 7.21.4.4 of the C99 standard, the invariant parameter is declared as const.
+
+```c
+int strncmp(const char *s1, const char *s2, size_t n); // Good: The invariant parameter is declared as const.
+```
+
+Note: Whether or not the pointer parameter is to be declared as 'const' depends on the function design, not on whether there is a "modify object" action in the function entity.
+
+### Rec 5.6 Ensure that the number of parameters in a function is less than or equal to 5.
+
+If a function has too many parameters, the function is easy to be affected by changes in external code, hindering maintenance. Too many function parameters will also increases the workload for testing.
+
+The number of parameters in a function must not exceed 5. If the number of parameters exceeds 5, consider the following:
+
+- Check whether the function can be split.
+- Check whether any related parameters can be combined and defined as a struct.
+
+## Inline Functions
+
+An inline function is a function optimization method introduced by C99. Function inlining can eliminate the overhead of function calls; thanks to inlining, combination with the called code is implemented, so that the compiler can achieve further code optimization from a larger perspective. The inline function is similar to a function-like macro. For details, see [Rec 6.1](#a6-1).
+
+### Rec 5.7 Ensure that the inline function contains no more than 10 lines (non-blank and non-comment).
+
+Defining a function as an inline function generally aims to improve performance, but it does not always improve performance. If the function body is short, function inlining can effectively reduce the size of the target code and improve the function execution efficiency.
+Vice versa, if the function body is large, inlining will cause expansion of the target code, especially when there are many call points.
+It is recommended that inline functions be controlled to within **10** lines.
+
+Do not abuse inline functions to improve performance. Avoid premature optimization. In general, a function can be defined as an inline function only when actual test data proves that the inlining achieves higher performance. Functions such as setter and getter functions, that are short and called frequently can be defined as inline functions.
+
+### Rule 5.3 Define inline functions that will be called by multiple source files in the header file.
+
+Inline functions are unfolded in compilation. Therefore, the inline function definition must be visible in each source file that calls this function.
+As shown in the following code, inline.h has only the declaration of the `SomeInlineFunc` function but no definition. The other.c file includes inline.h. As a result, inlining fails when `SomeInlineFunc` is called.
+
+inline.h
+
+```c
+inline int SomeInlineFunc(void);
+```
+
+inline.c
+
+```c
+inline int SomeInlineFunc(void)
+{
+ // Implementation code
+}
+```
+
+other.c
+
+```c
+#include "inline.h"
+int OtherFunc(void)
+{
+ int ret = SomeInlineFunc();
+}
+```
+
+Due to this restriction, if multiple source files need to call the same inline function, the definition of the inline function needs to be placed in the header file.
+The inline function implementation in **gnu89** differs from that in the **C99** standard. For compatibility, you can declare the function as **static inline**.
+
+# 6 Macros
+
+## Function-like Macros
+
+A function-like macro is a macro (as shown in the following example) similar to a function. It contains several statements to implement a specific function.
+
+```c
+#define ASSERT(x) do { \
+ if (!(x)) { \
+ printk(KERN_EMERG "assertion failed %s: %d: %s\n", \
+ __FILE__, __LINE__, #x); \
+ BUG(); \
+ } \
+} while (0)
+```
+
+### Use functions instead of function-like macros.
+
+Before defining a function-like macro, consider whether it can be replaced with a function. If so, you are advised to replace macros with functions.
+The disadvantages of the function-like macro are as follows:
+
+- Function-like macros haves no type check, which is not as strict as the function call check. For the example code, see [Below](#macro_lack_of_type_check__example).
+- If macro parameters are not calculated during macro expansion, unexpected results may be generated. For details, see [Rule 6.1](#r6-1) and [Rule 6.3](#r6-3).
+- The macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#r6-2) may be generated.
+- There are high skill requirements on the proper use of macros (see the following rules), for example, the usage of `#` and parentheses affects readability.
+- Extensions of some macros can only be implemented by specific compilers in specific scenarios, such as `statement expression` of `gcc`, reducing the portability.
+- After the macro is expanded at the pre-compilation stage, it is invisible during subsequent compilation, linking, and debugging. Macros that contain multiple lines are expanded into a line. Function-like macros are difficult to debug, interrupt, and locate in the case of bugs.
+- Macros containing a large number of statements must be expanded at each call point. If there are many call points, the code will be expanded.
+
+Example code of a function-like macro lacking type check:
+
+```c
+#define MAX(a, b) (((a) < (b)) ? (b) : (a))
+
+int Max(int a, int b)
+{
+ return (a < b) ? b : a;
+}
+
+int TestMacro(void)
+{
+ unsigned int a = 1;
+ int b = -1;
+
+ (void)printf("MACRO: max of a(%u) and b(%d) is %d\n", a, b, MAX(a, b));
+ (void)printf("FUNC : max of a(%u) and b(%d) is %d\n", a, b, Max(a, b));
+ return 0;
+}
+```
+
+Due to the lack of type check, the comparison between `a` and `b` in `MAX` is changed to a comparison ignoring the sign status. The result is **a \< b**. The output is as follows:
+
+```
+MACRO: max of a(1) and b(-1) is -1
+FUNC : max of a(1) and b(-1) is 1
+```
+
+The function does not have the preceding macro disadvantages. However, compared with macros, the biggest disadvantage is that the execution efficiency is not as high (increasing the overhead of function calls and the difficulty of compiler optimization).
+Therefore, the C99 standard introduces inline functions (gcc introduces inline functions ahead of this standard).
+
+The inline function is similar to the macro, as it is also expanded at the call point. The difference is that inline functions are expanded during compilation.
+Inline functions have the advantages of both functions and macros:
+
+- Strict type checking is performed for inline functions and functions.
+- The parameter of an inline function/function is calculated only once.
+- Inline functions are unfolded in place and there is no overhead for function calls.
+- Inline functions are better optimized than standard functions.
+
+For performance-sensitive code, consider using inline functions instead of function-like macros.
+Functions and inline functions cannot completely replace function-like macros, because function-like macros are more suitable for certain scenarios.
+For example, in a log scenario, using a function-like macro with variable parameters and default parameters is more convenient.
+
+```c
+int ErrLog(const char *file, unsigned long line, const char *fmt, ...);
+#define ERR_LOG(fmt, ...) ErrLog(__FILE__, __LINE__, fmt, ##__VA_ARGS__)
+```
+
+### Rule 6.1 When a macro is defined, macro parameters must use complete parentheses.
+
+The macro parameter is replaced by text only when the macro is expanded. The value is calculated when the macro is compiled. After the text replacement, the statements contained in the macro are combined with called code.
+The expression after combination may result in a different result than expected, especially when the macro parameter is in an expression.
+
+The following is an incorrect format:
+
+```c
+#define SUM(a, b) a + b // Bad.
+```
+
+When the macro is used, the execution result is inconsistent with the expected result.
+`100 / SUM(2, 8)` is expanded to `(100 / 2) + 8`. The expected result is `100 / (2 + 8)`.
+This problem can be solved by adding parentheses to the entire expression, as shown in the following:
+
+```c
+#define SUM(a, b) (a + b) // Bad.
+```
+
+However, this method has the following problems:
+`SUM(1 << 2, 8)` is extended to `1 << (2 + 8)` (because the priority of `<<` is lower than that of `+`), which is inconsistent with the expected result `(1 << 2) + 8`.
+
+To solve this problem, add parentheses to each macro parameter, as shown in the following:
+
+```c
+#define SUM(a, b) (a) + (b) // Bad.
+```
+
+The third scenario is as follows: `SUM(2, 8) * 10` . The result after the extension is `(2) + ((8) * 10)`, which is inconsistent with the expected result `(2 + 8) * 10`.
+
+In conclusion, the correct format is as follows:
+
+```c
+#define SUM(a, b) ((a) + (b)) // Good.
+```
+
+But avoid abusing parentheses. As shown in the following, adding parentheses to a single identifier or a positive number is meaningless.
+
+```c
+#define SOME_CONST 100 // Good: No parentheses needed for a single positive number.
+#define ANOTHER_CONST (-1) // Good: Parentheses needed for a negative number.
+
+#define THE_CONST SOME_CONST // Good: No parentheses needed for a single identifier.
+```
+
+Notes:
+
+- Macro parameters in '#', '##' operation do not need parentheses.
+- Macro parameters which participating in string splicing do not need parentheses.
+- If a macro parameter is used as a separate part in one side of an assignment expression (including +=, -=, etc.), parentheses are not required.
+- If a macro parameter is used as a separate part in comma expressions, functions or macro call lists, parentheses are not required.
+
+Example:
+
+```c
+#define MAKE_STR(x) #x // No parentheses for 'x'
+
+#define HELLO_STR(obj) "Hello, " obj // No parentheses for 'obj'
+
+#define ADD_3(sum, a, b, c) (sum = (a) + (b) + (c)) // 'a', 'b', and 'c' need parentheses, while 'sum' does not.
+
+#define FOO(a, b) Bar((a) + 1, b) // 'a' needs parentheses, while 'b' does not.
+```
+
+### Rule 6.2 Implementation statements of function-like macros that contain multiple statements must be placed in a do-while(0).
+
+Macros do not have code blocks. Macros do not have code blocks. When a macro is expanded at the call point, the expressions and variables defined in the macro are integrated into the calling code. As a result, variable name conflict and segmentation of macro statements may occur. Use do-while(0) to add a boundary to the macro so that the macro has an independent scope. In addition, a single statement can be formed by combining the macro with a semicolon (;) to avoid this problem.
+
+The following macro is incorrect:
+
+```c
+// Not Good.
+#define FOO(x) \
+ (void)printf("arg is %d\n", (x)); \
+ DoSomething((x));
+```
+
+When the macro is called as shown in the following example code, the for loop only executes the first statement of the macro, and the next statement of the macro is executed only after the loop ends.
+
+```c
+for (i = 1; i < 10; i++)
+ FOO(i);
+```
+
+To solve the preceding problem, use braces to enclose the statements defined by `FOO`.
+
+```c
+#define FOO(x) { \
+ (void)printf("arg is %d\n", (x)); \
+ DoSomething((x)); \
+}
+```
+
+The brackets are not associated with semicolons (;). The semicolon following the braces is another statement.
+In the following code example, the "suspended else' compilation error message is displayed.
+
+```c
+if (condition)
+ FOO(10);
+else
+ FOO(20);
+```
+
+The correct format is to wrap the executed body using a do-while(0), as shown in the following:
+
+```c
+// Good.
+#define FOO(x) do { \
+ (void)printf("arg is %d\n", (x)); \
+ DoSomething((x)); \
+} while (0)
+```
+
+Exception:
+
+- Macros that contain 'break' or 'continue' statements can be treated as exceptions. Do use these macros carefully.
+- An exception can be made when the macro contains an incomplete statement. For example, use a macro to encapsulate the conditional part of the for loop.
+- An exception can be a non-multiple statement, or a single if/for/while/switch statement.
+
+### Rule 6.3 Do not pass expressions with side effects to a function-like macro.
+
+Since macros are replaced by text, if a function-like macro uses the same macro parameter multiple times and transfers expressions with side effects as macro parameters, unexpected results may occur.
+As shown in the following example, the macro `SQUARE` is normal, but the `a++` expression with side effects is passed to the macro. As a result, the value of `a` is different from the expected value after the `SQUARE` macro is executed.
+
+```c
+#define SQUARE(a) ((a) * (a))
+
+int a = 5;
+int b;
+b = SQUARE(a++); // Bad: 'a' is added twice.
+```
+
+`SQUARE(a++)` is expanded to `((a++) * (a++))` the variable `a` is added twice, and its value is `7` instead of the expected `6`.
+
+The correct format is as follows:
+
+```c
+b = SQUARE(a);
+a++; // Result: a = 6, which is added only once.
+```
+
+In addition, if the macro parameter contains a function call, the function may be called repeatedly after the macro is expanded.
+If the function execution results are the same, it is a waste; if the results are different, the execution result may not meet the expected value.
+
+### Rec 6.2 Exercise caution when you use the statements such as return, goto, continue, and break in a function-like macro definition.
+
+In a macro, the process changing statements, such as return, goto, continue, and break. While they can simplify the code, they hide the real process, which hinders understanding and causes resource leakage.
+
+First, the macro encapsulation of the statement 'return' can easily lead to excessive encapsulation and use.
+As shown in the following code, the judgment of `status` is a part of the main process. After being encapsulated in macros, the purpose is not intuitive. The `RETURN_IF` macro is ignored, causing a confused understanding.
+
+```c
+#define LOG_AND_RETURN_IF_FAIL(ret, fmt, ...) do { \
+ if ((ret) != OK) { \
+ (void)ErrLog(fmt, ##__VA_ARGS__); \
+ return (ret); \
+ } \
+} while (0)
+
+#define RETURN_IF(cond, ret) do { \
+ if (cond) { \
+ return (ret); \
+ } \
+} while (0)
+
+ret = InitModuleA(a, b, &status);
+LOG_AND_RETURN_IF_FAIL(ret, "Init module A failed!"); // OK.
+
+RETURN_IF(status != READY, ERR_NOT_READY); // Bad: The most important logic is not obvious.
+
+ret = InitModuleB(c);
+LOG_AND_RETURN_IF_FAIL(ret, "Init module B failed!"); // OK.
+```
+
+Second, if return is encapsulated in a macro, it may also cause a memory leak. Example is as follows:
+
+```c
+#define CHECK_PTR(ptr, ret) do { \
+ if ((ptr) == NULL) { \
+ return (ret); \
+ } \
+} while (0)
+
+...
+
+mem1 = MemAlloc(...);
+CHECK_PTR(mem1, ERR_CODE_XXX);
+
+mem2 = MemAlloc(...);
+CHECK_PTR(mem2, ERR_CODE_XXX); // Wrong: Memory leak.
+```
+
+If `mem2` fails to apply for memory, the `CHECK_PTR` will return a message instead of releasing `mem1`.
+Besides, the name of the `CHECK_PTR` macro is not good. The macro name only reflects the check action and does not specify the result. Readers can see that a failure is returned when the pointer is null only after viewing the macro implementation. It's not inherently obvious.
+
+In summary: It is not recommended to encapsulate statements that change control flow, such as return, goto, continue, and break in macro definitions.
+However, these macros can be used such as return value judgment as an exception.
+
+Note: **Macro names must contain descriptive keywords if statements that will change control flow such as return, goto, continue, and break are used.**
+
+### Rec 6.3 Ensure that function-like macros contain no more than 10 lines (not including blank lines and comments).
+
+A big problem of the function-like macro is that it is more difficult to debug and locate than the function, especially when the macro is too long.
+Macro expansion will also lead to more compiled code. It is recommended that function-like macros contain no more than 10 lines.
+
+# 7 Variables
+
+In C language coding, variables are the most important except for functions.
+When using a variable, you should always follow the principle of "single responsibility".
+By scope, variables can be classified into global variables and local variables.
+
+## Global Variables
+
+Do not use or avoid using global variables.
+In program design, global variables are variables that are accessible to all scopes. Using unnecessary global variables is generally considered a bad habit.
+
+Disadvantages of global variables:
+
+- Destroys the independence and portability of a function. Functions can be dependent on global variables and increased coupling results.
+- Reduces readability and maintainability. When multiple functions read and write to global variables, their values may not be determinate, which is unfavorable for comprehension and maintenance.
+- In a concurrent programming environment, global variables will hinder reentry of functions. Additional synchronization protection must be added to ensure data security.
+
+If unavoidable, the read and write of global variables should be encapsulated in a centralized manner.
+
+### Rule 7.1 Do not use global variables as interfaces between modules.
+
+Global variables are for the internal implementation of modules and should not be exposed as interfaces.
+Global variables should be as centralized as possible. If the data of this module needs to be disclosed to external modules, a function as an interface to this data should be provided.
+
+## Local Variables
+
+### Rule 7.2 Do not use uninitialized variables as rvalues.
+
+The variable here refers to a local dynamic variable, and also includes a memory block obtained on a memory heap.
+Because their initial values are unpredictable, it is prohibited to use them directly as rvalues without effective initialization.
+
+```c
+void Foo(...)
+{
+ int data;
+ Bar(data); // Bad: Uninitialized variables are used as rvalues.
+ ...
+}
+```
+
+If there are different branches, ensure that all branches are initialized before being used as rvalues.
+
+```c
+void Foo(...)
+{
+ int data;
+ if (...) {
+ data = 100;
+ }
+ Bar(data); // Bad: This value is not initialized in some branches.
+ ...
+}
+```
+
+Uninitialized rvalues can be found by generic static check tools.
+For example, the PCLint tool reports a warning for the following two examples.
+
+> Warning 530: Symbol 'data' (line ...) not initialized Warning 644: Variable 'data' (line ...) may not have been initialized
+
+### Rule 7.3 Forbid invalid and redundant variable initialization.
+
+If the initial value is not determined before initialization is performed, it is not concise but not secure, which may introduce problems that are more difficult to discover.
+
+Common redundant initialization:
+
+```c
+int cnt = 0; // Bad: Redundant initialization. It will be overwritten by later initialization.
+...
+cnt = GetXxxCnt();
+...
+```
+
+Variables with conditional values can be initialized to default values during definition.
+
+```c
+char *buf = NULL; // Good: NULL as the default value
+if (condition) {
+ buf = malloc(MEM_SIZE);
+}
+...
+if (buf != NULL) { // Check whether memory has been allocated.
+ free(buf);
+}
+```
+
+Even worse, redundant clearing for arrays may affect the performance.
+
+```c
+char buf[VERY_BIG_SIZE] = {0};
+memset(buf, 0, sizeof(buf)); // Bad: Redundant clearing
+```
+
+Invalid initialization, which hides a more severe problem:
+
+```c
+void Foo(...)
+{
+ int data = 0; // Bad: regular initialization
+
+ UseData(data); // UseData should be placed after GetData.
+ data = GetData(...); // Get data.
+ ...
+}
+```
+
+In the preceding code, if 0 is not assigned before initialization, the static check tool can help find the problem of "direct use without being initialized".
+However, due to invalid initialization, the defect of placing "UseData" before "GetData" cannot be easily found.
+
+Therefore, simple code should be written to initialize variables or memory blocks as required.
+
+The C99 does not limit the definition position of local variables to before the first statement in a function. That is, a variable can now be defined close to a variable.
+This concise approach not only limits the scope of the variable scope, but also solves the problem of how to initialize the variable when it is defined.
+If this compilation environment is supported, you are advised to define local variables in this way.
+
+**Exception:**
+**As 'Secure Coding Standard' required, pointers, resource variables, and boolean variables can be treated as exceptions of this rule.**
+
+### Rule 7.4 Do not use magic numbers.
+
+The so-called magic numbers are the numbers that are unintelligible and difficult to understand.
+The magic number is not a concept that can be defined literally. It varies depending on context and service knowledge.
+
+For example, the number 12 varies in different contexts.
+`type = 12;` is not intelligible, but `month = year * 12;` can be understood.
+The number 0 is sometimes seen as a magic number. For example, the `status = 0;` cannot truly express any status information.
+
+Solution:
+Comments can be added for numbers that are used only once.
+For numbers that are used multiple times, macro or const variables must be defined and self-commented with symbolic naming.
+
+The following cases are forbidden:
+The name is not used to explain the meaning of a number, for example, `#define ZERO 0`.
+The value is limited by the name, for example, `#define XX_TIMER_INTERVAL_300MS 300`.
+
+# 8 Programming Practice
+
+## Expressions
+
+### Rec 8.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged.
+
+When a variable is compared with a constant, placing the constant on the left, for example, `if (MAX == v)` does not read naturally, and `if (MAX > v)` is more difficult to understand.
+The constant should be placed on the right according to the normal reading order and habit. The expression is written as follows:
+
+```c
+if (v == MAX) ...
+if (v < MAX) ...
+```
+
+There are special cases: for example, the expression `if (MIN < v && v < MAX)` is used to check for a range. This first constant should be placed on the left.
+
+You do not need to worry about accidentally writing '==' as '=' because a compilation alarm will be generated for `if (v = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable.
+
+### A full expression containing an increment (++) or decrement (--) operator should have no other using of the variable.
+
+In an expression containing a variable increment or decrement operation, if the variable is referenced again, the result is not explicitly defined in the C standard, which may vary between compilers or different versions of the same compiler.
+For better portability, you should not make any assumptions about the operation sequence not defined in any standards.
+
+Note that this problem cannot be solved by using parentheses because it is not a problem of priority.
+
+Example:
+
+```c
+x = b[i] + i++; // Bad: b[i] operation and i++, the order is not clear.
+```
+
+The correct way is to add a separate line of increment or decrement:
+
+```c
+x = b[i] + i;
+i++; // Good: Single line.
+```
+
+Function parameter:
+
+```c
+Func(i++, i); // Bad: When passing the second parameter, it is not sure whether the increment operation has occurred.
+```
+
+The correct way:
+
+```c
+i++; // Good: Single line.
+x = Func(i, i);
+```
+
+### Rec 8.2 Use parentheses to specify the sequence of expressions, instead of using the default priority.
+
+Parentheses can be used to better emphasize the purpose of used operators. This will prevent program errors due to the inconsistency between default priority and the intended design.
+However, too many parentheses muddy the code, reducing readability. Use them moderately.
+
+Parentheses are recommended when expressions contain operators that are not commonly used and are confusing, such as bitwise operators.
+
+```c
+c = (a & 0xFF) + b; /* Parentheses are required while using bit operators. */
+```
+
+## Statements
+
+### Rule 8.2 The switch statement must have a 'default' branch.
+
+In most cases, the 'default' branch exists in the switch statement to ensure that there is a default processing action when the case tag is missing.
+
+Exception:
+If the switch condition variable is of the enumeration type and the case branches cover all values, then the default branch is redundant.
+A modern compiler can check whether the case branch of some enumerated values is missing in the switch statement. A warning will be displayed.
+
+```c
+enum Color {
+ RED,
+ BLUE
+};
+
+// The switch condition variable is an enumerated value. Therefore, you do not need to add the 'default' processing branch.
+switch (color) {
+ case RED:
+ DoRedThing();
+ break;
+ case BLUE:
+ DoBlueThing();
+ ...
+ break;
+}
+```
+
+### Rec 8.3 Exercise caution when using the goto statement.
+
+The goto statement destroys the structure of the program, so you'd better not use the goto statement unless you really need it. You can only jump to statements following the goto statement, and only within the one function.
+
+The goto statement is used to implement function return to a single point within a function.
+If a function has a large number of identical logics that cannot be encapsulated, for example, repeated file execution, the processed part of code after the file operation failure (for example, closing the file handle and releasing memory that is dynamically applied for) is usually placed in the last part of the function body. And the goto statement is placed right before these. In this way, the code becomes clear and concise. It can also be encapsulated in functions or macros, but doing so makes code less straightforward.
+
+Example:
+
+```c
+// Good: Use a goto statement to implement function return at a single point.
+int SomeInitFunc(void)
+{
+ void *p1;
+ void *p2 = NULL;
+ void *p3 = NULL;
+
+ p1 = malloc(MEM_LEN);
+ if (p1 == NULL) {
+ goto EXIT;
+ }
+
+ p2 = malloc(MEM_LEN);
+ if (p2 == NULL) {
+ goto EXIT;
+ }
+
+ p3 = malloc(MEM_LEN);
+ if (p3 == NULL) {
+ goto EXIT;
+ }
+
+ DoSomething(p1, p2, p3);
+ return 0; // OK.
+
+EXIT:
+ if (p3 != NULL) {
+ free(p3);
+ }
+ if (p2 != NULL) {
+ free(p2);
+ }
+ if (p1 != NULL) {
+ free(p1);
+ }
+ return -1; // Failed!
+}
+```
+
+## Type Conversion
+
+### Rec 8.4 Minimize unnecessary type conversion and forced conversion.
+
+When the data type is forcibly changed, the meaning of the data and the value after conversion may change. If details are not considered, potential risks may be generated.
+
+In the following assignment, most compilers do not generate warnings, but the values are slightly changed.
+
+```c
+char ch;
+unsigned short int exam;
+
+ch = -1;
+exam = ch; // Bad: Compilers does not generate any warnings. In this case, the value of exam is 0xFFFF.
+```
\ No newline at end of file
diff --git a/docs-en/contribute/OpenHarmony-cpp-coding-style-guide.md b/docs-en/contribute/OpenHarmony-cpp-coding-style-guide.md
new file mode 100644
index 0000000000000000000000000000000000000000..8a7ecbad0ca50c514f6b14380fca47613f505468
--- /dev/null
+++ b/docs-en/contribute/OpenHarmony-cpp-coding-style-guide.md
@@ -0,0 +1,2821 @@
+# C++ Coding Style Guide
+
+## Purpose
+Rules are not perfect. Disabling useful features in specific situations may affect code implementation. However, the rules are formulated "to help most programmers to get more benefits". If a rule is found unhelpful or difficult to follow in team coding, please send your feedback to us so we can improve the rule accordingly.
+Before referring to this guide, you are expected to have the following basic capabilities for C++. It is not for a beginner that wants to learn about C++.
+1. Have a general knowledge of ISO standards for C++.
+2. Be familiar with the basic features of C++, including those of C++ 03/11/14/17.
+3. Have a general knowledge of the C++ Standard Library.
+
+## General Principles
+Code must meet the requirements for readability, maintainability, security, reliability, testability, efficiency, and portability while ensuring functionality correctness.
+
+## Key Points
+1. C++ programming style, such as naming and typesetting.
+2. C++ modular design, including how to design header files, classes, interfaces, and functions.
+3. Best practices of C++ features, including constants, type casting, resource management, and templates.
+4. Best practices of modern C++, including conventions that can improve code maintainability and reliability in C++ 11/14/17.
+
+
+## Conventions
+**Rule**: a regulating principle that must be followed during programming.
+
+**Recommendation**: a guideline that must be considered during programming.
+
+This document is applicable to standard C++ versions (C++ 03/11/14/17) unless otherwise specified in the rule.
+
+## Exceptions
+It is necessary to understand the reason for each rule or recommendation and to try and comply with them.
+However, some rules and recommendations have exceptions.
+
+The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for the exception.
+Try to avoid exceptions because they affect the code consistency. Exceptions to 'Rules' should be very rare.
+
+The style consistency principle is preferred in the following case:
+When you modify external open source or third-party code, the existing code specifications prevail.
+
+# 2 Naming
+## General Naming Rules
+__CamelCase__
+CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, with no intervening spaces or punctuation.
+There are two conventions: UpperCamelCase and lowerCamelCase.
+
+
+| Type | Naming Style |
+| ---------------------------------------- | ---------------------------------------- |
+| Class Type, Struct Type, Enumeration Type, and Union Type Definitions, Scope Name | UpperCamelCase |
+| Functions (Including Global Functions, Scope Functions, and Member Functions) | UpperCamelCase |
+| Global Variables (Including Variables of the Global and Namespace Scopes, Namespace Variables, and Class Static Variables), Local Variables, Function Parameters, and Class, Struct, and Union Member Variables | lowerCamelCase |
+| Macro, Constant, Enumerated Value, goto Tag | All caps, separated with underscores (`_`) |
+
+Note:
+**Constant** indicates the variables of the basic, enumeration, or character string type modified by const or constexpr in the global scope, the namespace scope, and the scope of a static member of a class.
+**Variable** indicates the variables excluding those defined in **Constant**. These variables use the lowerCamelCase style.
+
+## File Names
+### Recommendation 2.2.1 Use .cpp as the C++ file name extension and .h as the header file name extension.
+It is recommended that you use .h as the name extension of a header file so that the header file can be directly compatible with C and C++.
+It is recommended that you use .cpp as the name extension of an implementation file. In this way, you can directly distinguish C++ code from C code.
+
+At present, there are some other file name extensions used by programmers:
+
+- Header files: .hh, .hpp, .hxx
+- Implementation files: .cc, .cxx, .C
+
+If your project team uses a specific file name extension, you can continue to use it and keep the style consistent.
+This document uses .h and .cpp extensions.
+
+
+### Recommendation 2.2.2 Keep C++ file names the same as the class name.
+The names of the C++ header file and the C++ implementation file must be the same as the class name. Use the CamelCase or Kernel style and keep the style consistent.
+
+For example, if there is a class named DatabaseConnection, the corresponding file names are as follows:
+- database_connection.h
+- database_connection.cpp
+
+The naming rules of struct, namespace, and enumeration definition files are similar to the rules above.
+
+## Function Names
+Functions are named in UpperCamelCase. Generally, the verb or verb-object structure is used.
+```cpp
+class List {
+public:
+ void AddElement(const Element& element);
+ Element GetElement(const unsigned int index) const;
+ bool IsEmpty() const;
+};
+
+namespace Utils {
+ void DeleteUser();
+}
+```
+
+## Type Names
+
+Types are named in the UpperCamelCase style.
+All types, such as classes, structs, unions, typedefs, and enumerations, use the same conventions. For example:
+```cpp
+// classes, structs and unions
+class UrlTable { ...
+class UrlTableTester { ...
+struct UrlTableProperties { ...
+union Packet { ...
+
+// typedefs
+typedef std::map PropertiesMap;
+
+// enums
+enum UrlTableErrors { ...
+```
+
+For namespace naming, UpperCamelCase is recommended.
+```cpp
+// namespace
+namespace OsUtils {
+
+namespace FileUtils {
+
+}
+
+}
+```
+
+
+### Recommendation 2.4.1 Do not abuse typedef or #define to alias basic types.
+Unless otherwise specified, do not use typedef or #define to redefine a basic value type.
+The basic types found in the `` header file are preferable.
+
+| Signed Type | Unsigned Type | Description |
+| ----------- | ------------- | ---------------------------------------- |
+| int8_t | uint8_t | The signed or unsigned 8-bit integer type. |
+| int16_t | uint16_t | The signed or unsigned 16-bit integer type. |
+| int32_t | uint32_t | The signed or unsigned 32-bit integer type. |
+| int64_t | uint64_t | The signed or unsigned 64-bit integer type. |
+| intptr_t | uintptr_t | The signed or unsigned integer type large enough to hold a pointer. |
+
+
+## Variable Names
+General variables are named in lowerCamelCase, including global variables, function parameters, local variables, and member variables.
+```cpp
+std::string tableName; // Good: Recommended style.
+std::string tablename; // Bad: Forbidden style.
+std::string path; // Good: When there is only one word, lowerCamelCase (all lowercase) is used.
+```
+
+### Rule 2.5.1 Add the prefix 'g_' to global variables. Do not add a prefix to a static variable.
+Global variables should be used as little as possible, and special attention should be paid to the use of global variables. This prefix highlights global variables so that developers can be more careful when handling them.
+- Global static variables and global variables are named in the same way.
+- Static variables and common local variables in functions are named in the same way.
+- Static member variables and common member variables of classes are named in the same way.
+
+```cpp
+int g_activeConnectCount;
+
+void Func()
+{
+ static int packetCount = 0;
+ ...
+}
+```
+
+### Rule 2.5.2 Name member variables in classes based on the three styles of the lowerCamelCase and maintain a uniform coding style for a product or project.
+
+```cpp
+class Foo {
+private:
+ std::string fileName_; // Add the _ postfix, similar to the K&R naming style.
+};
+```
+Use the lowerCamelCase style and do not add prefixes or suffixes to name a member variable of the struct or union type. Keep the naming style consistent with that for a local variable.
+
+## Macro, Constant, and Enumeration Names
+For macros and enumerated values, use all caps separated with underscores (`_`).
+In the global scope, constants of named and unnamed namespaces and static member constants should be capitalized and separated with underscores (`_`). Local constants and ordinary const member variables use the lowerCamelCase naming style.
+
+```cpp
+#define MAX(a, b) (((a) < (b))? (b): (a)) // Though examples of Macro names are made, you are not advised to use macros to implement this function.
+
+enum BaseColor { // Note: Enumerated types are named in the UpperCamelCase style, while their values are all capitalized and separated with underscores (_).
+ RED,
+ DARK_RED,
+ GREEN,
+ LIGHT_GREEN
+};
+
+int Func(...)
+{
+ const unsigned int bufferSize = 100; // Local variable
+ char *p = new char[bufferSize];
+ ...
+}
+
+namespace Utils {
+ const unsigned int DEFAULT_FILE_SIZE_KB = 200; // Global variable
+}
+
+```
+
+# 3 Formatting
+
+## Line Length
+
+### Recommendation 3.1.1 Each line of code should contain a maximum of 120 characters.
+** Note: **It is recommended that the number of characters in each line not exceed 120. It is recommended that the number of characters in each line not exceed 120. If the line of code exceeds the permitted length, wrap the line appropriately.
+
+Exception:
+- If a one-line comment contains a command or URL of more than 120 characters, you can keep the line for ease in using copy, paste, and search using the grep command.
+- The length of an `#include` statement can contain a long path exceeding 120 characters, but this should be avoided if possible.
+- The error information in preprocessor directives can exceed the permitted length.
+ Put the error information of preprocessor directives in one line to facilitate reading and understanding even if the line contains more than 120 characters.
+```cpp
+#ifndef XXX_YYY_ZZZ
+#error Header aaaa/bbbb/cccc/abc.h must only be included after xxxx/yyyy/zzzz/xyz.h, because xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+#endif
+```
+
+## Indentation
+
+### Rule 3.2.1 Use spaces to indent and indent 4 spaces at a time.
+Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent.
+Currently, almost all IDEs support automatic expansion of a Tab to 4 spaces upon pressing the tab key. Please configure your IDE to do so.
+
+## Braces
+### Rule 3.3.1 Use the K&R indentation writing style.
+__K&R style__
+When a line break is required, the left brace of a function (excluding the lambda statement) starts a new line. One space should be placed between the statement and the brace.
+The right brace starts a new line and nothing else is placed on the line, unless it is followed by the remaining part of the same statement, for example, "while" in the do statement, "else" or "else if" in the if statement, a comma, and a semicolon.
+
+For example:
+```cpp
+struct MyType { // Follow the statement to the end, and indent one space.
+ ...
+};
+
+int Foo(int a)
+{ // The left brace of the function starts a new line, nothing else is placed on the line.
+ if (...) {
+ ...
+ } else {
+ ...
+ }
+}
+```
+The reasons for recommending this style are as follows:
+
+- Code is more compact.
+- Placing the brace at the end of the statement makes the code more continuous in reading rhythm than starting a new line.
+- This style complies with mainstream norms and habits of programming languages.
+- Most modern IDEs have an automatic code indentation, alignment and display. Placing the brace at the end of a line does not impact understanding.
+
+
+If no function body is inside the braces, the braces can be put on the same line.
+```cpp
+class MyClass {
+public:
+ MyClass() : value_(0) {}
+
+private:
+ int value_;
+};
+```
+
+## Function Declarations and Definitions
+
+### Rule 3.4.1 The return type and the function name of a function declaration or definition must be on the same line. When the length of the function parameter list exceeds the permitted length, a line break is required and parameters must be aligned appropriately.
+When a function is declared or defined, the return value type of the function should be on the same line as the function name. If the line length permits, the function parameters should be placed on the same line. Otherwise, the function parameters should be wrapped and properly aligned.
+The left parenthesis of a parameter list should always be on the same line as the function name. The right parenthesis always follows the last parameter.
+
+The following is an example of line breaks:
+```cpp
+ReturnType FunctionName(ArgType paramName1, ArgType paramName2) // Good: All are in the same line.
+{
+ ...
+}
+
+ReturnType VeryVeryVeryLongFunctionName(ArgType paramName1, // Each added parameter starts on a new line because the line length limit is exceeded.
+ ArgType paramName2, // Good: aligned with the previous parameter.
+ ArgType paramName3)
+{
+ ...
+}
+
+ReturnType LongFunctionName(ArgType paramName1, ArgType paramName2, // Parameters are wrapped because the line length limit is exceeded.
+ ArgType paramName3, ArgType paramName4, ArgType paramName5) // Good: After the line break, 4 spaces are used for indentation.
+{
+ ...
+}
+
+ReturnType ReallyReallyReallyReallyLongFunctionName( // The line length cannot accommodate even the first parameter, and a line break is required.
+ ArgType paramName1, ArgType paramName2, ArgType paramName3) // Good: After the line break, 4 spaces are used for indentation.
+{
+ ...
+}
+```
+
+## Function Calls
+### Rule 3.5.1 A function call parameter list should be placed on one line. When the parameter list exceeds the line length and requires a line break, the parameters should be properly aligned.
+A function call parameter list should be placed on one line. When the parameter list exceeds the line length and requires a line break, the parameters should be properly aligned.
+The left parenthesis always follows the function name, and the right parenthesis always follows the last parameter.
+
+The following are examples of proper line breaks:
+```cpp
+ReturnType result = FunctionName(paramName1, paramName2); // Good: All function parameters are on one line.
+
+ReturnType result = FunctionName(paramName1,
+ paramName2, // Good: aligned with the previous parameter
+ paramName3);
+
+ReturnType result = FunctionName(paramName1, paramName2,
+ paramName3, paramName4, paramName5); // Good: Parameters are wrapped. After the line break, 4 spaces are used for indentation.
+
+ReturnType result = VeryVeryVeryLongFunctionName( // The line length cannot accommodate even the first parameter, and a line break is required.
+ paramName1, paramName2, paramName3); // After the line break, 4 spaces are used for indentation.
+```
+
+If some of the parameters called by a function are associated with each other, you can group them for better understanding.
+```cpp
+// Good: The parameters in each line represent a group of data structures with strong correlation. They are placed on a line for ease of understanding.
+int result = DealWithStructureLikeParams(left.x, left.y, // A group of related parameters.
+ right.x, right.y); // Another group of related parameters.
+```
+
+## if Statements
+
+### Rule 3.6.1 Use braces to include an if statement.
+We require that all if statements use braces, even if there is only one statement.
+
+Reasons:
+- The logic is intuitive and easy to read.
+- It is less prone to mistakes when new code is added to the existing if statement.
+- If function-like macros are used in a conditional statement, it is less prone to mistakes (in case the braces are missing when macros are defined).
+
+```cpp
+if (objectIsNotExist) { // Good: Braces are added to a single-line conditional statement.
+ return CreateNewObject();
+}
+```
+### Rule 3.6.2 Place if, else, and else if keywords on separate lines.
+If there are multiple branches in a conditional statement, they should be placed on separate lines.
+
+Good example:
+
+```cpp
+if (someConditions) {
+ DoSomething();
+ ...
+} else { // Good: Put the if and else keywords on separate lines.
+ ...
+}
+```
+
+Bad example:
+
+```cpp
+if (someConditions) { ... } else { ... } // Bad: The if and else keywords are put on the same line.
+```
+
+## Loop Statements
+### Rule 3.7.1 Use braces after loop statements.
+Similar to if statements, we require that the for and while loop statements contain braces, even if the loop body is empty or there is only one loop statement.
+```cpp
+for (int i = 0; i < someRange; i++) { // Good: Braces are used.
+ DoSomething();
+}
+```
+```cpp
+while (condition) {} // Good: The while loop body is empty. Braces should be used.
+```
+```cpp
+while (condition) {
+ continue; // Good: The continue keyword highlights the end of the empty loop. Braces should be used.
+}
+```
+
+Bad example:
+```cpp
+for (int i = 0; i < someRange; i++)
+ DoSomething(); // Bad: Braces are mandatory.
+```
+```cpp
+while (someCondition) ; // Bad: Using a semicolon here will make people misunderstand that it is a part of the while statement and not the end to it.
+```
+
+## Switch Statements
+### Rule 3.8.1 Indent case and default in a switch statement with four spaces.
+The indentation style of the switch statement is as follows:
+```cpp
+switch (var) {
+ case 0: // Good: Indented
+ DoSomething1(); // Good: Indented
+ break;
+ case 1: { // Good: Braces are added.
+ DoSomething2();
+ break;
+ }
+ default:
+ break;
+}
+```
+
+```cpp
+switch (var) {
+case 0: // Bad: case is not indented.
+ DoSomething();
+ break;
+default: // Bad: default is not indented.
+ break;
+}
+```
+
+## Expressions
+
+### Recommendation 3.9.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of a line.
+A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped at an operator of a lower priority or a connector, and the operator or connector is placed at the end of the line.
+Placing these at the end of a line indicates that the operation is to be continued on the next line.
+For example:
+
+// Assume that the first line exceeds the length limit.
+```cpp
+if (currentValue > threshold && // Good: After the line break, the logical-AND operators are placed at the end of the line.
+ someConditionsion) {
+ DoSomething();
+ ...
+}
+
+int result = reallyReallyLongVariableName1 + // Good
+ reallyReallyLongVariableName2;
+```
+After an expression is wrapped, ensure that the lines are aligned appropriately or indented with 4 spaces. See the following example.
+
+```cpp
+int sum = longVaribleName1 + longVaribleName2 + longVaribleName3 +
+ longVaribleName4 + longVaribleName5 + longVaribleName6; // Good: indented with 4 spaces
+
+int sum = longVaribleName1 + longVaribleName2 + longVaribleName3 +
+ longVaribleName4 + longVaribleName5 + longVaribleName6; // Good: The lines are aligned.
+```
+## Variable Assignment
+
+### Rule 3.10.1 Multiple variable definitions and assignment statements cannot be written on one line.
+Each line should have only one variable initialization statement. It is easier to read and understand.
+
+```cpp
+int maxCount = 10;
+bool isCompleted = false;
+```
+
+Bad example:
+
+```cpp
+int maxCount = 10; bool isCompleted = false; // Bad: Multiple variable initialization statements must be separated on different lines. Each variable initialization statement occupies one line.
+int x, y = 0; // Bad: Multiple variable definitions must be separated on different lines. Each definition occupies one line.
+
+int pointX;
+int pointY;
+...
+pointX = 1; pointY = 2; // Bad: Multiple variable assignment statements must be separated on different lines.
+```
+Exception: Multiple variables can be declared and initialized in the for loop header, if initialization statement (C++17), and structured binding statement (C++17). Multiple variable declarations in these statements have strong associations. Forcible division into multiple lines may cause problems such as scope inconsistency and separation of declaration from initialization.
+
+## Initialization
+Initialization is applicable to structs, unions, and arrays.
+
+### Rule 3.11.1 When an initialization list is wrapped, ensure that the line after the break is indented and aligned properly.
+If a structure or array initialization list is wrapped, the line after the break is indented with four spaces.
+Choose the wrap location and alignment style for best comprehension.
+
+```cpp
+const int rank[] = {
+ 16, 16, 16, 16, 32, 32, 32, 32,
+ 64, 64, 64, 64, 32, 32, 32, 32
+};
+```
+
+## Pointers and References
+### Recommendation 3.12.1 The pointer type `*` follows a variable name or type. There can be only one space to the side of it.
+Pointer naming: There can be only one space next to `*`.
+```cpp
+int* p = NULL; // Good
+int *p = NULL; // Good
+
+int*p = NULL; // Bad
+int * p = NULL; // Bad
+```
+
+Exception: When a variable is modified by const or restrict, `*` cannot follow the variable or type.
+```cpp
+const char * const VERSION = "V100";
+```
+
+### Recommendation 3.12.2 The reference type `&` follows a variable name or type. There can be only one space to the side of it.
+Reference naming: There can be only one space around `&`.
+```cpp
+int i = 8;
+
+int& p = i; // Good
+int &p = i; // Good
+int*& rp = pi; // Good: The reference type `*&` follows the type.
+int *&rp = pi; // Good: The reference type `*&` follows the variable name.
+int* &rp = pi; // Good: The pointer type `*` follows the type and the eference type `&` follows the variable name.
+
+int & p = i; // Bad
+int&p = i; // Bad
+```
+
+## Preprocessor Directives
+### Rule 3.13.1 The number sign (#) that starts a preprocessor directive must be at the beginning of the line and can be indented in nested preprocessor directives.
+The number sign (#) that starts a preprocessor directive must be at the beginning of the line even through the preprocessor directive is inside a function.
+
+```cpp
+#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) // Good: "#" is at the beginning of the line.
+#define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: "#" is at the beginning of the line.
+#else
+#define ATOMIC_X86_HAS_CMPXCHG16B 0
+#endif
+
+
+int FunctionName()
+{
+ if (someThingError) {
+ ...
+#ifdef HAS_SYSLOG // Good: Even in the function body, "#" is at the beginning of the line.
+ WriteToSysLog();
+#else
+ WriteToFileLog();
+#endif
+ }
+}
+```
+The nested preprocessor directives starting with `#` can be indented and aligned based on a standardized style.
+
+```cpp
+#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
+ #define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: wrapped for easier comprehension
+#else
+ #define ATOMIC_X86_HAS_CMPXCHG16B 0
+#endif
+```
+
+## Whitespace
+### Rule 3.14.1 Ensure that horizontal spaces are used to highlight keywords and important information, and avoid unnecessary whitespace.
+Horizontal spaces are used to highlight keywords and important information. Spaces are not allowed at the end of each code line. The general rules are as follows:
+
+- Add spaces after keywords such as if, switch, case, do, while, and for.
+- Do not add spaces after the left parenthesis or before the right parenthesis.
+- For expressions enclosed by braces, either add a space on either side or avoid a space on either side.
+- Do not add spaces after any unary operator (& * + - ~ !).
+- Add a space to the left and right sides of each binary operator (= + -< > * /% | & ^ <= >= == !=).
+- Add spaces to the left and right sides of a ternary operator (? :).
+- Do not add spaces between a prefix or suffix increment (++) or decrement (--) operator and a variable.
+- Do not add spaces before or after a struct member operator (. ->).
+- Do not add spaces before commas. Add spaces after commas.
+- Do not add spaces between a template or type conversion operator (<>) and a type.
+- Do not add spaces before or after a domain operator (::).
+- Determine whether to add spaces before and after a colon (:) based on the actual situation.
+
+In normal cases:
+```cpp
+void Foo(int b) { // Good: A space is added before the left brace.
+
+int i = 0; // Good: During variable initialization, there should be spaces before and after =. Do not leave a space before the semicolon.
+
+int buf[BUF_SIZE] = {0}; // Good: Spaces are not added in braces.
+```
+
+Function definition and call:
+```cpp
+int result = Foo(arg1,arg2);
+ ^ // Bad: A space should be added after the comma.
+
+int result = Foo( arg1, arg2 );
+ ^ ^ // Bad: Spaces should not be added after the left parenthesis or before the right parenthesis.
+```
+
+Pointer and Address Operator
+```cpp
+x = *p; // Good: There is no space between the operator * and the pointer p.
+p = &x; // Good: There is no space between the operator & and the variable x.
+x = r.y; // Good: When a member variable is accessed through the operator (.), no space is added.
+x = r->y; // Good: When a member variable is accessed through the operator (->), no space is added.
+```
+
+Other Operators:
+```cpp
+x = 0; // Good: There is a space before and after the assignment operator (=).
+x = -5; // Good: There is no space between the minus sign (–) and the number.
+++x; //Good: Do not add spaces between a prefix or suffix increment (++) or decrement (--) operator and a variable..
+x--;
+
+if (x && !y) // Good: There is a space before and after the Boolean operator. There is no space between the ! operator and the variable.
+v = w * x + y / z; // Good: There is a space before and after the binary operator.
+v = w * (x + z); // Good: There is no space before or after the expression in the parentheses.
+
+int a = (x < y) ? x : y; // Good: Ternary operator. There is a space before and after ? and :
+```
+
+Loops and Conditional Statements:
+```cpp
+if (condition) { // Good: There is a space between the if keyword and the left parenthesis, and no space before or after the conditional statement in the parentheses.
+ ...
+} else { // Good: There is a space between the else keyword and the left brace.
+ ...
+}
+
+while (conditions) {} // Good: There is a space between the while keyword and the left parenthesis. There is no space before or after the conditional statement in the parentheses.
+
+for (int i = 0; i < someRange; ++i) { // Good: There is a space between the for keyword and the left parenthesis, and after the semicolon.
+ ...
+}
+
+switch (condition) { // Good: There is a space after the switch keyword.
+ case 0: // Good: There is no space between the case condition and the colon.
+ ...
+ break;
+ ...
+ default:
+ ...
+ break;
+}
+```
+
+Templates and Conversions
+```cpp
+// Angle brackets (< and >) are not adjacent to space. There is no space before < or between > and (.
+vector x;
+y = static_cast(x);
+
+// There can be a space between the type and the pointer operator. Keep the spacing style consistent.
+vector x;
+```
+
+Scope Operators
+```cpp
+std::cout; // Good: Namespace access. Do not leave spaces.
+
+int MyClass::GetValue() const {} // Good: Do not leave spaces in the definition of member functions.
+```
+
+Colons
+```cpp
+// Scenarios when space is required
+
+// Good: // Add a space before or after the colon in a derived class definition.
+class Sub : public Base {
+
+};
+
+// Add a space before or after the colon in the initialization list of a constructor function.
+MyClass::MyClass(int var) : someVar_(var)
+{
+ DoSomething();
+}
+
+// Add a space before or after the colon in a bit-field.
+struct XX {
+ char a : 4;
+ char b : 5;
+ char c : 4;
+};
+```
+
+```cpp
+// Scenarios when space is not required
+
+// Good: // No space is added before or after the colon next to a class access permission (public or private).
+class MyClass {
+public:
+ MyClass(int var);
+private:
+ int someVar_;
+};
+
+// No space is added before or after the colon in a switch statement.
+switch (value)
+{
+ case 1:
+ DoSomething();
+ break;
+ default:
+ break;
+}
+```
+
+Note: Currently, all IDEs support automatic deletion of spaces at the end of a line. Please configure your IDE correctly.
+
+### Recommendation 3.14.1 Use blank lines only when necessary to keep code compact.
+
+There must be as few blank lines as possible so that more code can be displayed for easy reading. Recommendations:
+- Add blank lines according to the correlation between lines.
+- Consecutive blank lines are not allowed inside functions, type definitions, macros, and initialization expressions.
+- A maximum of **two** consecutive blank lines can be used.
+- Do not add blank lines on the first and last lines of a code block in braces. This recommendation is not applicable to code block in braces of a namespace.
+
+```cpp
+int Foo()
+{
+ ...
+}
+
+
+
+int bar() {// Bad: More than one blank lines are used between two function definitions.
+{
+ ...
+}
+
+
+if (...) {
+ // Bad: Do not add blank lines on the first and last lines of a code block.
+ ...
+ // Bad: Do not add blank lines on the first and last lines of a code block.
+}
+
+int Foo(...)
+{
+ // Bad: Do not add blank lines before the first statement in a function body.
+ ...
+}
+```
+
+## Classes
+### Rule 3.15.1 Class access specifier declarations are in the sequence: public, protected, private. Indent these specifiers to the same level as the class keyword.
+```cpp
+class MyClass : public BaseClass {
+public: // Not indented.
+ MyClass(); // Indented with 4 spaces.
+ explicit MyClass(int var);
+ ~MyClass() {}
+
+ void SomeFunction();
+ void SomeFunctionThatDoesNothing()
+ {
+ }
+
+ void SetVar(int var) { someVar_ = var; }
+ int GetVar() const { return someVar_; }
+
+private:
+ bool SomeInternalFunction();
+
+ int someVar_;
+ int someOtherVar_;
+};
+```
+
+In each part, it is recommended that similar statements be put together and in the following order: Type (including typedef, using, nested structs and classes), Constant, Factory Function, Constructor, Assignment Operator, Destructor, Other Member Function, and Data Member
+
+
+### Rule 3.15.2 The constructor initialization list must be on the same line or wrapped and aligned with four spaces of indentation.
+```cpp
+// If all variables can be placed on the same line
+MyClass::MyClass(int var) : someVar_(var)
+{
+ DoSomething();
+}
+
+// If the variables cannot be placed on the same line
+// Wrapped at the colon and indented with four spaces
+MyClass::MyClass(int var)
+ : someVar_(var), someOtherVar_(var + 1) // Good: Add a space after the comma.
+{
+ DoSomething();
+}
+
+// If an initialization list needs to be placed in multiple lines, put each member on a separate line and align between lines.
+MyClass::MyClass(int var)
+ someVar(var), // Four spaces of indentation.
+ someOtherVar_(var + 1)
+{
+ DoSomething();
+}
+```
+
+# 4 Comments
+Generally, clear architecture and good naming are recommended to improve code readability, and comments are provided only when necessary.
+Comments are used to help readers quickly understand code. Therefore, **comments should be provided for the sake of readers**.
+
+Comments must be concise, clear, and unambiguous, ensuring that information is complete and not redundant.
+
+**Comments are as important as code**.
+When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the function and intention of code, rather than repeating code.
+When modifying the code, ensure that the comments are consistent with the modified code. It is not polite to modify only code and keep the old comments, which will undermine the consistency between code and comments, and may confuse or even mislead readers.
+
+Comments should be made in English.
+
+## Comment Style
+
+In C++ code, both ` /* */` and ` // ` can be used for commenting.
+Comments can be classified into different types, such as file header comments, function header comments, and code comments. This is based on their purposes and positions.
+Comments of the same type must keep a consistent style.
+
+Note: Example code in this document uses comments in the `//` format only to better describe the rules and recommendations. This does not mean this comment format is better.
+
+## File Header Comments
+### Rule 4.2.1 File header comments must contain the copyright notice.
+
+/*
+ * Copyright (c) 2020 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+## Function Header Comments
+### Rule 4.3.1 Function header comments with no content are forbidden.
+Not all functions need function header comments.
+For information that cannot be described by function signatures, add function header comments.
+
+Function header comments are placed above the function declaration or definition. Use one of the following styles:
+Use '//' to start the function header.
+
+```cpp
+// Single-line function header
+int Func1(void);
+
+// Multi-line function header
+// Second line
+int Func2(void);
+```
+
+Use `/* */` to start the function header.
+```cpp
+/* Single-line function header */
+int Func1(void);
+
+/*
+ * Another single-line function header
+ */
+int Func2(void);
+
+/*
+ * Multi-line function header
+ * Second line
+ */
+int Func3(void);
+```
+Use function names to describe functions, and add function header comments if necessary.
+Do not write useless or redundant function headers. Do not write empty function headers with no content.
+
+The function header comment content will depend on the function and includes but is not limited to: a function description, return value, performance constraints, usage comments, memory conventions, algorithm implementation, reentering requirements.
+In the function interface declaration in the external header file, the function header comment should clearly describe important and useful information.
+
+Good example:
+
+```cpp
+/*
+ * The number of written bytes is returned. If -1 is returned, the write operation failed.
+ * Note that the memory buffer should be released by the caller.
+ */
+int WriteString(const char *buf, int len);
+```
+
+Bad example:
+```cpp
+/*
+ * Function name: WriteString
+ * Function: Write a character string.
+ * Parameters:
+ * Return value:
+ */
+int WriteString(const char *buf, int len);
+```
+Problems:
+
+- The 'Parameters' and 'Return value' have no content.
+- The function name is redundant.
+- The most import thing, that is, who needs to release the buffer, is not clearly stated.
+
+## Code Comments
+### Rule 4.4.1 Code comments are placed above or on the right of the corresponding code.
+### Rule 4.4.2 There must be a space between the comment character and the comment content. At least one space is required between the comment and code if the comment is placed to the right of code.
+Comments placed above code should be indented the same as that of the code.
+Use one of the following styles:
+Use "//".
+```cpp
+
+// Single-line comment
+DoSomething();
+
+// Multi-line comment
+// Second line
+DoSomething();
+```
+
+Use `/* */`.
+```cpp
+/* Single-line comment */
+DoSomething();
+
+/*
+ * Multi-line comment in another mode
+ * Second line
+ */
+DoSomething();
+```
+Leave at least one space between the code and the comment on the right. It is recommended that no more than four spaces be left.
+You can use the Tab key to indent 1–4 spaces.
+
+Select and use one of the following styles:
+
+```cpp
+int foo = 100; // Comment on the right
+int bar = 200; /* Comment on the right */
+```
+It is more appealing sometimes when the comment is placed on the right of code and the comments and code are aligned vertically.
+After the alignment, ensure that the comment is 1–4 spaces away from the widest line of code.
+For example:
+
+```cpp
+const int A_CONST = 100; /* Related comments of the same type can be aligned vertically. */
+const int ANOTHER_CONST = 200; /* Leave spaces after code to align comments vertically. */
+```
+When the comment on the right exceeds the line width, consider placing the comment above the code.
+
+### Rule 4.4.3 Delete unused code segments. Do not comment them out.
+Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects.
+The correct method is to delete unnecessary code directly. If necessary, consider porting or rewriting the code.
+
+Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /* */, //, #if 0, #ifdef NEVER_DEFINED, and so on.
+
+### Recommendation 4.4.1 Delivered code cannot contain a TODO/TBD/FIXME comment.
+TODO/TBD comments are used to describe required improvements and supplements.
+FIXME comments are used to describe defects that need fixing.
+They should have a standardized style, which facilitates text search. For example:
+
+```cpp
+// TODO(): XX
+// FIXME: XX
+```
+
+
+# 5 Header Files
+## Header File Responsibility
+A header file is an external interface of a module or file. The design of a header file shows most of the system design.
+The interface declaration for most functions is more suitable placed in the header file, but implementation (except inline functions) cannot be placed in the header file. Functions, macros, enumerations, and structure definitions that need to be used in .cpp files cannot be placed in the header file.
+The header responsibility should be simple. An overly complex header file will make dependencies complex and cause long compilation times.
+
+### Recommendation 5.1.1 Each .cpp file should have a .h file with the same name. It should be used to declare the classes and interfaces that need to be exposed externally.
+Generally, each .cpp file has a corresponding .h file. This .cpp file is used to store the function declarations, macro definitions, and class definitions that are to be exposed.
+If a .cpp file does not need to open any interface externally, it should not exist.
+Exception: __An entry point (for example, the file where the main function is located), unit tests, and dynamic libraries __
+
+For example:
+```cpp
+// Foo.h
+
+#ifndef FOO_H
+#define FOO_H
+
+class Foo {
+public:
+ Foo();
+ void Fun();
+
+private:
+ int value_;
+};
+
+#endif
+```
+
+```cpp
+// Foo.cpp
+#include "Foo.h"
+
+namespace { // Good: The declaration of the internal function is placed in the header of the .cpp file, and has been limited to the unnamed namespace or static scope.
+ void Bar()
+ {
+ }
+}
+
+...
+
+void Foo::Fun()
+{
+ Bar();
+}
+```
+
+## Header File Dependency
+### Rule 5.2.1 Header file cyclic dependency is forbidden.
+An example of cyclic dependency (also known as circular dependency) is: a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any of these header files is modified, all code containing a.h, b.h, and c.h needs to be recompiled.
+For a unidirectional dependency, for example if: a.h contains b.h, b.h contains c.h, and c.h does not contain any header file, modifying a.h does not mean that we need to recompile the source code for b.h or c.h.
+
+The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization.
+
+
+### Rule 5.2.2 Header files should have #define guards to prevent multiple inclusion.
+To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once.
+
+When defining a protection character, comply with the following rules:
+1) The protection character uses a unique name.
+2) Do not place code or comments (except for file header comments) before or after the protected part.
+
+Example: Assume that the timer.h file of the timer module is in the timer/include/timer.h directory. Perform the following operations to safeguard the timer.h file:
+
+```cpp
+#ifndef TIMER_INCLUDE_TIMER_H
+#define TIMER_INCLUDE_TIMER_H
+...
+#endif
+```
+
+### Rule 5.2.3 It is prohibited to reference external function interfaces and variables in extern declaration mode.
+Interfaces provided by other modules or files can be used only by including header files.
+Using external function interfaces and variables in extern declaration mode may cause inconsistency between declarations and definitions when external interfaces are changed.
+In addition, this kind of implicit dependency may cause architecture corruption.
+
+Cases that do not comply with specifications:
+
+// a.cpp content
+```cpp
+extern int Fun(); // Bad: Use external functions in extern mode.
+
+void Bar()
+{
+ int i = Fun();
+ ...
+}
+```
+
+// b.cpp content
+```cpp
+int Fun()
+{
+ // Do something
+}
+```
+Should be changed to:
+
+// a.cpp content
+```cpp
+#include "b.h" // Good: Use the interface provided by other .cpp by including its corresponding header file.
+
+void Bar()
+{
+ int i = Fun();
+ ...
+}
+```
+
+// b.h content
+```cpp
+int Fun();
+```
+
+// b.cpp content
+```cpp
+int Fun()
+{
+ // Do something
+}
+```
+In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used.
+For example:
+When performing unit testing on an internal function, you can use the extern declaration to reference the tested function.
+When a function needs to be stubbed or patched, the function can be declared using extern.
+
+### Rule 5.2.4 Do not include header files in extern "C".
+If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the nesting of extern "C". If there are too many nested layers, compilation errors may occur.
+
+When C and C++ programmings are used together and if extern "C" includes a header file, the original intent behind the header file may be hindered. For example, when the link specifications are modified incorrectly.
+
+For example, assume that there are two header files a.h and b.h.
+
+// a.h content
+```cpp
+...
+#ifdef __cplusplus
+void Foo(int);
+#define A(value) Foo(value)
+#else
+void A(int)
+#endif
+```
+// b.h content
+```cpp
+...
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "a.h"
+void B();
+
+#ifdef __cplusplus
+}
+#endif
+```
+
+Using the C++ preprocessor to expand b.h, the following information is displayed:
+```cpp
+extern "C" {
+ void Foo(int);
+ void B();
+}
+```
+
+According to the author of a.h, the function Foo is a C++ free function following the "C++" link specification.
+However, because `#include "a.h"` is placed inside `extern "C"` in b.h, the link specification of function Foo is changed incorrectly.
+
+Exception:
+In the C++ compilation environment, if you want to reference the header file of pure C, the C header files should not contain `extern "C"`. The non-intrusive approach is to include the C header file in `extern "C"`.
+
+### Recommendation 5.2.1 Use `#include` instead of a forward declaration to include header files.
+A forward declaration is for the declaration of classes, functions, and templates and is not meant for its definition.
+
+- Advantages:
+ 1. Forward declarations can save compilation time. Redundant `#include `statements force the compiler to expand more files and process more input.
+ 2. Forward declarations can save unnecessary recompilation time. The use of #include will force your code to be recompiled multiple times due to unrelated changes in header files.
+- Disadvantages:
+ 1. Forward declarations hide dependency relationship. When a header file is modified, user code will skip the necessary recompilation process.
+ 2. A forward declaration may be broken by subsequent changes to the library. Forward declarations of functions and templates sometimes prevent header file developers from changing APIs. For example, widening a formal parameter type, adding a template parameter with a default value, and so on.
+ 3. Forward declaration of symbols from the namespace `std::` is seen as undefined behavior (as specified in the C++ 11 standard specification).
+ 4. Forward declaration of multiple symbols from a header file can be more verbose than simply including (#include) the header.
+ 5. Structuring code only for forward declaration (for example, using pointer members instead of object members) can make the code more complex and slower.
+ 6. It is difficult to determine whether a forward declaration or `#include` is needed. In some scenarios, replacing `#include` with a forward declaration may cause unexpected results.
+
+Therefore, we should avoid using forward declarations as much as possible. Instead, we use the #include statement to include a header file and ensure dependency.
+
+# 6 Scopes
+
+## Namespaces
+
+### Recommendation 6.1.1 For code that does not need to be exported from the .cpp file, you are advised to use an unnamed namespace for encapsulation or use static to modify the variables, constants, or functions that need hiding.
+In the C++ 2003 standard, using static to modify the external availability of functions and variables was marked as deprecated. Therefore, unnamed namespaces are the recommended method.
+
+Main Reasons:
+1. There are too many meanings for static in C++: static function member variable, static member function, static global variable, and static function local variable. Each of them has special processing.
+2. Static can only be used to define variables, constants, and functions that are not referenced outside the current .cpp file, while namespaces can also be used to encapsulate types.
+3. Use a namespace to control the scope instead of using both static and namespaces.
+4. Unnamed namespaces can be used to instantiate templates rather than functions modified by the static keyword.
+
+Do not use unnamed namespaces or static in header files.
+
+```cpp
+// Foo.cpp
+
+namespace {
+ const int MAX_COUNT = 20;
+ void InternalFun(){};
+}
+
+void Foo::Fun()
+{
+ int i = MAX_COUNT;
+
+ InternalFun();
+}
+
+```
+
+### Rule 6.1.1 Do not use "using" to import namespace in a header file or before #include statements.
+Note: Using "using" to import namespace will affect any subsequent code and may cause symbol conflicts.
+Example:
+
+```cpp
+// Header file a.h
+namespace NamespaceA {
+ int Fun(int);
+}
+```
+
+```cpp
+// Header file b.h
+namespace NamespaceB {
+ int Fun(int);
+}
+
+using namespace NamespaceB;
+
+void G()
+{
+ Fun(1);
+}
+```
+
+```cpp
+// Source code a.cpp
+#include "a.h"
+using namespace NamespaceA;
+#include "b.h"
+
+void main()
+{
+ G(); // "using namespace NamespaceA" before #include "b.h", will cause conflicts when calling NamespaceA::Fun and NamespaceB::Fun.
+}
+```
+
+Using "using" to import a symbol or define an alias in a header file is allowed in customized namespaces of modules, but is prohibited in the global namespace.
+```cpp
+// foo.h
+
+#include
+using fancy::string; // Bad: It is prohibited to import symbols to the global namespace.
+
+namespace Foo {
+ using fancy::string; // Good: Symbols can be imported in customized namespaces of modules.
+ using MyVector = fancy::vector; // Good: In C++11, aliases can be defined in customized namespaces.
+}
+```
+
+
+## Global Functions and Static Member Functions
+
+### Recommendation 6.2.1 Use namespaces to manage global functions. If global functions are closely tied to a class, you can use static member functions.
+Note: Placing non-member functions in a namespace avoids polluting the global scope. Do not use "class + static member function" to simply manage global functions. If a global function is closely tied to a class, it can be used as a static member function of the class.
+
+If you need to define some global functions for a .cpp file, use unnamed namespaces for management.
+```cpp
+namespace MyNamespace {
+ int Add(int a, int b);
+}
+
+class File {
+public:
+ static File CreateTempFile(const std::string& fileName);
+};
+```
+
+## Global Constants and Static Member Constants
+
+### Recommendation 6.3.1 Use namespaces to manage global constants. If global constants are closely tied to a class, you can use static member constants.
+Note: Placing global constants in a namespace avoids polluting the global scope. Do not use "class + static member constant" to simply manage global constants. If a global constant is closely tied to a class, it can be used as a static member constant of the class.
+
+If you need to define some global constants only for a .cpp file, use unnamed namespaces for management.
+```cpp
+namespace MyNamespace {
+ const int MAX_SIZE = 100;
+}
+
+class File {
+public:
+ static const std::string SEPARATOR;
+};
+```
+
+## Global Variables
+
+### Recommendation 6.4.1 Do not use global variables. Use the singleton pattern instead.
+Note: Global variables can be modified and read, which results in data coupling between production code and the global variables.
+```cpp
+int g_counter = 0;
+
+// a.cpp
+g_counter++;
+
+// b.cpp
+g_counter++;
+
+// c.cpp
+cout << g_counter << endl;
+```
+
+Singleton
+```cpp
+class Counter {
+public:
+ static Counter& GetInstance()
+ {
+ static Counter counter;
+ return counter;
+ } // Simple example of a singleton implementation
+
+ void Increase()
+ {
+ value_++;
+ }
+
+ void Print() const
+ {
+ std::cout << value_ << std::endl;
+ }
+
+private:
+ Counter() : value_(0) {}
+
+private:
+ int value_;
+};
+
+// a.cpp
+Counter::GetInstance().Increase();
+
+// b.cpp
+Counter::GetInstance().Increase();
+
+// c.cpp
+Counter::GetInstance().Print();
+```
+
+After the singleton is implemented, there is a unique global instance, which can functions as a global variable. However, the singleton provides better encapsulation.
+
+Exception: In some cases, the scope of a global variable is contained inside a module. Multiple instances of the same global variable may exist, and each module holds one copy. In this case, a singleton cannot be used as it is limited to one instance.
+
+# 7 Classes
+
+## Constructors, Copy/Move Constructors, Copy/Move Assignment Operators, and Destructors
+Constructors, copy/move constructors, copy/move assignment operators, and destructors provide lifetime management methods for objects.
+- Constructor: `X()`
+- Copy constructor: `X(const X&)`
+- Copy assignment operator: `operator=(const X&)`
+- Move constructor: `X (X&&)` *Provided in versions later than C++ 11*.
+- Move assignment operator: `operator=(X&&)` *Provided in versions later than C++ 11*.
+- Destructor: `~X()`
+
+### Rule 7.1.1 The member variables of a class must be initialized explicitly.
+Note: If a class has members but no constructor and a default constructor is defined, the compiler will automatically generate a constructor, but it will not initialize member variables. The content of each object is uncertain.
+
+Exception:
+- If the member variables in a class have a default constructor, explicit initialization is not required.
+
+Example: The following code has no constructor, and private data members cannot be initialized:
+```cpp
+class Message {
+public:
+ void ProcessOutMsg()
+ {
+ //…
+ }
+
+private:
+ unsigned int msgID_;
+ unsigned int msgLength_;
+ unsigned char* msgBuffer_;
+ std::string someIdentifier_;
+};
+
+Message message; // The message member is not initialized.
+message.ProcessOutMsg(); // Potential risks exist in subsequent use.
+
+// Therefore, it is necessary to define a default constructor as follows:
+class Message {
+public:
+ Message() : msgID_(0), msgLength_(0), msgBuffer_(NULL)
+ {
+ }
+
+ void ProcessOutMsg()
+ {
+ // …
+ }
+
+private:
+ unsigned int msgID_;
+ unsigned int msgLength_;
+ unsigned char* msgBuffer_;
+ std::string someIdentifier; // The member variable has a default constructor. Therefore, explicit initialization is not required.
+};
+```
+
+### Recommendation 7.1.1 Initialization during declaration (C++ 11) and initialization using the constructor initialization list are preferred for member variables.
+Note: Initialization during declaration (C++11) is preferred because initialized values of member variables can be easily understood. If initialized values of certain member variables are relevant to constructors, or C++ 11 is not supported, the constructor initialization list is used preferentially to initialize these member variables. Compared with the assignment statements in constructors, code of the constructor initialization list is simpler and has higher performance, and can be used to initialize constant and reference members.
+
+```cpp
+class Message {
+public:
+ Message() : msgLength(0) { // Good: The constructor initialization list is preferred.
+ {
+ msgBuffer = NULL; // Bad: Values cannot be assigned in constructors.
+ }
+
+private:
+ unsigned int msgID{0}; // Good: Used in C++11.
+ unsigned int msgLength_;
+ unsigned char* msgBuffer_;
+};
+```
+
+### Rule 7.1.2 Declare single-parameter constructors as explicit to prevent implicit conversion.
+Note: If a single-parameter constructor is not declared as explicit, it will become an implicit conversion function.
+Example:
+
+```cpp
+class Foo {
+public:
+ explicit Foo(const string& name): name_(name)
+ {
+ }
+private:
+ string name_;
+};
+
+
+void ProcessFoo(const Foo& foo){}
+
+int main(void)
+{
+ std::string test = "test";
+ ProcessFoo(test); // Compiling failed.
+ return 0;
+}
+```
+
+The preceding code fails to be compiled because the parameter required by `ProcessFoo` is of the Foo type, which mismatch with the input string type.
+
+If the explicit keyword of the Foo constructor is removed, implicit conversion is triggered and a temporary Foo object is generated when `ProcessFoo` is called with the string parameter. Usually, this implicit conversion is confusing and bugs are apt to be hidden, due to unexpected type conversion. Therefore, single-parameter constructors require explicit declaration.
+
+### Rule 7.1.3 If copy/move constructors and copy/move assignment operators are not needed, clearly prohibit them.
+Note: If users do not define it, the compiler will generate copy constructors and copy assignment operators, move constructors and move assignment operators (move semantic functions will be available in versions later than C++ 11).
+If we do not use copy constructors or copy assignment operators, explicitly delete them.
+
+1. Set copy constructors or copy assignment operators to private and do not implement them.
+```cpp
+class Foo {
+private:
+ Foo(const Foo&);
+ Foo& operator=(const Foo&);
+};
+```
+2. Use delete provided by C++ 11. For details, see Rule 10.1.3 in chapter 10 Modern C++ Features.
+
+### Rule 7.1.4 Copy constructors and copy assignment operators should be implemented or forbidden together.
+Both copy constructors and copy assignment operators provide copy semantics. They should be implemented or hidden together.
+
+```cpp
+// The copy constructor and the copy assignment operator are implemented together.
+class Foo {
+public:
+ ...
+ Foo(const Foo&);
+ Foo& operator=(const Foo&);
+ ...
+};
+
+// The copy constructor and the copy assignment operator are both set to default, as supported by C++ 11.
+class Foo {
+public:
+ Foo(const Foo&) = default;
+ Foo& operator=(const Foo&) = default;
+};
+
+// The copy constructor and the copy assignment operator are hidden together. You should use the delete keyword if C++11 features are available.
+class Foo {
+private:
+ Foo(const Foo&);
+ Foo& operator=(const Foo&);
+};
+```
+
+### Rule 7.1.5 Move constructors and move assignment operators should be implemented or hidden together.
+The move operation is added in C++ 11. If a class is required to support the move operation, move constructors and move assignment operators need to be implemented.
+
+Both move constructors and move assignment operators provide move semantics. They should be implemented or hidden together.
+```cpp
+// The copy constructor and the copy assignment operator are implemented together.
+class Foo {
+public:
+ ...
+ Foo(Foo&&);
+ Foo& operator=(Foo&&);
+ ...
+};
+
+// The copy constructor and the copy assignment operator are both set to default, as supported by C++ 11.
+class Foo {
+public:
+ Foo(Foo&&) = default;
+ Foo& operator=(Foo&&) = default;
+};
+
+// The copy constructor and the copy assignment operator are hidden together. You should use the delete keyword if C++11 features are available.
+class Foo {
+public:
+ Foo(Foo&&) = delete;
+ Foo& operator=(Foo&&) = delete;
+};
+```
+
+### Rule 7.1.6 It is prohibited to call virtual functions in constructors and destructors.
+Note: Calling a virtual function of the current object in a constructor or destructor will cause behaviors of non-polymorphism.
+In C++, a base class constructs only one complete object at a time.
+
+Example: Base indicates the base class, and Sub indicates the derived class.
+```cpp
+class Base {
+public:
+ Base();
+ virtual void Log() = 0; // Different derived classes call different log files.
+};
+
+Base::Base() // Base class constructor
+{
+ Log(); // Call the virtual function log.
+}
+
+class Sub : public Base {
+public:
+ virtual void Log();
+};
+```
+
+When running the following statement:
+`Sub sub;`
+The constructor of the derived class is executed first. However, the constructor of the base class is called first. Because the constructor of the base class calls the virtual function log, the log is in the base class version. The derived class is constructed only after the base class is constructed. As a result, behaviors of non-polymorphism are caused.
+This also applies to destructors.
+
+
+## Inheritance
+
+### Rule 7.2.1 Destructors of a base class should be declared as virtual.
+Note: Destructors of the derived class can be called during polymorphism invocation only when destructors of the base class are virtual.
+
+Example: There will be memory leak if destructors of the base class are not declared as virtual.
+```cpp
+class Base {
+public:
+ virtual std::string getVersion() = 0;
+
+ ~Base()
+ {
+ std::cout << "~Base" << std::endl;
+ }
+};
+```
+
+```cpp
+class Sub : public Base {
+public:
+ Sub() : numbers_(NULL)
+ {
+ }
+
+ ~Sub()
+ {
+ delete[] numbers_;
+ std::cout << "~Sub" << std::endl;
+ }
+
+ int Init()
+ {
+ const size_t numberCount = 100;
+ numbers_ = new (std::nothrow) int[numberCount];
+ if (numbers_ == NULL) {
+ return -1;
+ }
+
+ ...
+ }
+
+ std::string getVersion()
+ {
+ return std::string("hello!");
+ }
+private:
+ int* numbers_;
+};
+```
+
+```cpp
+int main(int argc, char* args[])
+{
+ Base* b = new Sub();
+
+ delete b;
+ return 0;
+}
+```
+Because destructors of the base class are not declared as virtual, only destructors of the base class are called when an object is destroyed. Destructors of the derived class Sub are not called. As a result, a memory leak occurs.
+
+
+### Rule 7.2.2 Do not use default parameter values for virtual functions.
+Note: In C++, virtual functions are dynamically bound, but the default parameters of functions are statically bound during compilation. This means that the function you finally execute is a virtual function that is defined in the derived class but uses the default parameter value in the base class. To avoid confusion and other problems caused by inconsistent default parameter declarations during overriding of virtual functions, it is prohibited to declare default parameter values for all virtual functions.
+Example: The default value of parameter "text" of the virtual function "Display" is determined at compilation time instead of runtime, which does not fit with polymorphism.
+```cpp
+class Base {
+public:
+ virtual void Display(const std::string& text = "Base!")
+ {
+ std::cout << text << std::endl;
+ }
+
+ virtual ~Base(){}
+};
+
+class Sub : public Base {
+public:
+ virtual void Display(const std::string& text = "Sub!")
+ {
+ std::cout << text << std::endl;
+ }
+
+ virtual ~Sub(){}
+};
+
+int main()
+{
+ Base* base = new Sub();
+ Sub* sub = new Sub();
+
+ ...
+
+ base->Display(); // The program output is as follows: Base! The expected output is as follows: Sub!
+ sub->Display(); // The program output is as follows: Sub!
+
+ delete base;
+ delete sub;
+ return 0;
+};
+```
+
+### Rule 7.2.3 Do not redefine inherited non-virtual functions.
+Note: Non-virtual functions cannot be dynamically bound (only virtual functions can be dynamically bound). You can obtain the correct result by operating on the pointer of the base class.
+
+Example:
+```cpp
+class Base {
+public:
+ void Fun();
+};
+
+class Sub : public Base {
+public:
+ void Fun();
+};
+
+Sub* sub = new Sub();
+Base* base = sub;
+
+sub->Fun(); // Call Fun of the derived class.
+base->Fun(); // Call Fun of the base class.
+//...
+
+```
+
+## Multiple Inheritance
+In the actual development process, multiple inheritance is seldom used because the following typical problems may occur:
+1. Data duplication and name ambiguity caused by "diamond" inheritance. C++ introduces virtual inheritance to solve these problems.
+2. In addition to "diamond" inheritance, names of multiple base classes may also conflict with each other, resulting in name ambiguity.
+3. If a derived class needs to be extended or needs to override methods of multiple base classes, the responsibilities of the derived classes are unclear and semantics are muddled.
+4. Compared with delegation, inheritance is seen as white box reuse, that is, a derived class can access the protected members of the base class, which leads to more coupling. Multiple inheritance, due to the coupling of multiple base classes, leads to even more coupling.
+
+Multiple inheritance has the following advantages:
+Multiple inheritance provides a simpler method for assembling and reusing multiple interfaces or classes.
+
+Therefore, multiple inheritance can be used only in the following cases:
+
+### Recommendation 7.3.1 Use multiple inheritance to implement interface separation and multi-role combination.
+If a class requires multiple interfaces, combine multiple separated interfaces by using multiple inheritance. This is similar to the Traits mixin of the Scala language.
+
+```cpp
+class Role1 {};
+class Role2 {};
+class Role3 {};
+
+class Object1 : public Role1, public Role2 {
+ // ...
+};
+
+class Object2 : public Role2, public Role3 {
+ // ...
+};
+
+```
+
+The C++ standard library has a similar implementation example:
+```cpp
+class basic_istream {};
+class basic_ostream {};
+
+class basic_iostream : public basic_istream, public basic_ostream {
+
+};
+```
+
+## Overloading
+
+Overload operators should be used when there are sufficient reasons, and they do not change the original perception of the operators. For example, do not use the plus sign (+) to perform subtraction.
+Operator overloading can make code more intuitive but has some disadvantages:
+- It is often mistaken that the operation is as fast as a built-in operator, which has no performance degradation.
+- There is no naming to aid debugging. It is more convenient to search by function name than by operator.
+- Overloading operators can cause confusion if behavior definitions are not intuitive (for example, if the "+" operator is used for subtraction).
+- The implicit conversion caused by the overloading of assignment operators may lead to entrenched bugs. Functions such as Equals () and CopyFrom () can be defined to replace the = and == operators.
+
+
+
+# 8 Functions
+## Function Design
+### Rule 8.1.1 Avoid long functions and ensure that each function contains no more than 50 lines (non-null and non-comment).
+A function should be displayed on one screen (no longer than 50 lines). It should do only one thing, and do it well.
+
+Long functions often mean that the functions are too complex to implement in more than one function, or overly detailed but not further abstracted.
+
+Exception: Some algorithms may be longer than 50 lines due to algorithm convergence and functional comprehensiveness.
+
+Even if a long function works very well now, once someone modifies it, new problems may occur. It might even cause bugs that are difficult to find.
+It is recommended that you split a long function into several functions that are simpler and easier to manage, facilitating comprehension and modification.
+
+## Inline Functions
+
+### Recommendation 8.2.1 An inline function cannot exceed 10 lines.
+**Note**: An inline function has the same characteristics of a normal function. The difference between an inline function and a normal function lies in the processing of function calls. When a general function is called, the program execution right is transferred to the called function, and then returned to the function that calls it. When an inline function is called, the invocation expression is replaced with an inline function body.
+
+Inline functions are only suitable for small functions with only 1-10 lines. For a large function that contains many statements, the function call and return overheads are relatively trivial and do not need the help of an inline function. Most compilers may abandon the inline mode and use the common method to call the function.
+
+If an inline function contains complex control structures, such as loop, branch (switch), and try-catch statements, the compiler may regard the function as a common function.
+**Virtual functions and recursive functions cannot be used as inline functions**.
+
+## Function Parameters
+
+### Recommendation 8.3.1 Use a reference instead of a pointer for function parameters.
+
+**Note**: A reference is more secure than a pointer because it is not empty and does not point to other targets. Using a reference stops the need to check for illegal null pointers.
+
+If a product is being developed for an older platform, the processing used by the old platform is preferred.
+Use const to avoid parameter modification, so that readers can clearly know that a parameter is not going to be modified. This greatly enhances code readability.
+
+Exception: When the input parameter is an array with an unknown compile-time length, you can use a pointer instead of a reference.
+
+### Recommendation 8.3.2 Use strongly typed parameters. Do not use void*.
+While different languages have their own views on strong typing and weak typing, it is generally believed that C and C++ are strongly typed languages. Since we use such a strongly typed language, we should keep to this style.
+An advantage of this is the compiler can find type mismatch problems at the compilation stage.
+
+Using strong typing helps the compiler find more errors for us. Pay attention to the usage of the FooListAddNode function in the following code:
+```cpp
+struct FooNode {
+ struct List link;
+ int foo;
+};
+
+struct BarNode {
+ struct List link;
+ int bar;
+}
+
+void FooListAddNode(void *node) // Bad: Here, the void * type is used to transfer parameters.
+{
+ FooNode *foo = (FooNode *)node;
+ ListAppend(&g_FooList, &foo->link);
+}
+
+void MakeTheList()
+{
+ FooNode *foo = NULL;
+ BarNode *bar = NULL;
+ ...
+
+ FooListAddNode(bar); // Wrong: In this example, the foo parameter was supposed to be transferred, but the bar parameter is accidentally transferred instead. However, no error is reported.
+}
+```
+
+1. You can use a template function to change the parameter type.
+2. A base class pointer can be used to implement this according to polymorphism.
+
+### Recommendation 8.3.3 A function can have a maximum of five parameters.
+If a function has too many parameters, it is apt to be affected by external changes, and therefore maintenance is affected. Too many function parameters will also increase the testing workload.
+
+If a function has more than five parameters, you can:
+- Split the function.
+- Combine related parameters into a struct.
+
+# 9 Other C++ Features
+
+## Constants and Initialization
+
+Unchanged values are easier to understand, trace, and analyze. Therefore, use constants instead of variables as much as possible. When defining values, use const as a default.
+
+### Rule 9.1.1 Do not use macros to replace constants.
+
+**Note**: Macros are a simple text replacement that is completed in the preprocessing phase. When an error is reported, the corresponding value is reported. During tracing and debugging, the value is also displayed instead of the macro name. A macro does not support type checking and is insecure. A macro has no scope.
+
+```cpp
+#define MAX_MSISDN_LEN 20 // Bad
+
+// Use const in C++.
+const int MAX_MSISDN_LEN = 20; // Good
+
+// In versions later than C++ 11, constexpr can be used.
+constexpr int MAX_MSISDN_LEN = 20;
+```
+
+### Recommendation 9.1.1 A group of related integer constants must be defined as an enumeration.
+
+**Note**: Enumerations are more secure than `#define` or `const int`. The compiler checks whether a parameter value is within the enumerated value range to avoid errors.
+
+```cpp
+// Good example:
+enum Week {
+ SUNDAY,
+ MONDAY,
+ TUESDAY,
+ WEDNESDAY,
+ THURSDAY,
+ FRIDAY,
+ SATURDAY
+};
+
+enum Color {
+ RED,
+ BLACK,
+ BLUE
+};
+
+void ColorizeCalendar(Week today, Color color);
+
+ColorizeCalendar(BLUE, SUNDAY); // Compilation error. The parameter type is incorrect.
+
+// Bad example:
+const int SUNDAY = 0;
+const int MONDAY = 1;
+
+const int BLACK = 0;
+const int BLUE = 1;
+
+bool ColorizeCalendar(int today, int color);
+ColorizeCalendar(BLUE, SUNDAY); // No error is reported.
+```
+
+When an enumeration value needs to correspond to a specific value, explicit value assignment is required during declaration. Otherwise, do not assign explicit values. This will prevent repeated assignment and reduce the maintenance workload (when adding and deleting members).
+
+```cpp
+// Good example: Device ID defined in the S protocol. It is used to identify a device type.
+enum DeviceType {
+ DEV_UNKNOWN = -1,
+ DEV_DSMP = 0,
+ DEV_ISMG = 1,
+ DEV_WAPPORTAL = 2
+};
+```
+
+Do not assign explicit values when enumeration is used internally, and only for classification.
+
+```cpp
+// Good example: Enumeration definition is used to identify session status in a program.
+enum SessionState {
+ INIT,
+ CLOSED,
+ WAITING_FOR_RESPONSE
+};
+```
+
+Try to avoid repeating enumeration values. If it is required, use the already defined enumeration values instead.
+
+```cpp
+enum RTCPType {
+ RTCP_SR = 200,
+ RTCP_MIN_TYPE = RTCP_SR,
+ RTCP_RR = 201,
+ RTCP_SDES = 202,
+ RTCP_BYE = 203,
+ RTCP_APP = 204,
+ RTCP_RTPFB = 205,
+ RTCP_PSFB = 206,
+ RTCP_XR = 207,
+ RTCP_RSI = 208,
+ RTCP_PUBPORTS = 209,
+ RTCP_MAX_TYPE = RTCP_PUBPORTS
+};
+```
+
+### Rule 9.1.2 Magic numbers cannot be used.
+So-called magic numbers are numbers that are unintelligible and difficult to understand.
+
+Some numbers can be understood based on context.
+For example, the number 12 varies in different contexts.
+type = 12; is not intelligible (and a magic number), but `month = year * 12`; can be understood, so we wouldn't really class this as a magic number.
+The number 0 is often seen as a magic number. For example, `status = 0`; cannot truly express any status information.
+
+Solution:
+Comments can be added for numbers that are used locally.
+For the numbers that are used multiple times, you must define them as constants and give them descriptive names.
+
+The following cases are forbidden:
+No symbol is used to explain the meaning of a number, for example, ` const int ZERO = 0`.
+The symbol name limits the value. For example, for example, `const int XX_TIMER_INTERVAL_300MS = 300`. Use `XX_TIMER_INTERVAL_MS` instead.
+
+### Rule 9.1.3 Ensure that a constant has only one responsibility.
+
+**Note**: A constant is used for only one specific function, that is, a constant cannot be used for multiple purposes.
+
+```cpp
+// Good example: For protocol A and protocol B, the length of the MSISDN is 20.
+const unsigned int A_MAX_MSISDN_LEN = 20;
+const unsigned int B_MAX_MSISDN_LEN = 20;
+
+// Using different namespaces:
+namespace Namespace1 {
+ const unsigned int MAX_MSISDN_LEN = 20;
+}
+
+namespace Namespace2 {
+ const unsigned int MAX_MSISDN_LEN = 20;
+}
+```
+
+### Rule 9.1.4 Do not use memcpy_s or memset_s to initialize non-POD objects.
+
+**Note**: `POD` is short for `Plain Old Data`, which is a concept introduced in the C++ 98 standard (ISO/IEC 14882, first edition, 1998-09-01). The `POD` types include the original types and aggregate types such as `int`, `char`, `float`, `double`, `enumeration`, `void`, and pointer. Encapsulation and object-oriented features cannot be used (for example, user-defined constructors, assignment operators, destructors, base classes, and virtual functions).
+
+For non-POD classes, such as class objects of non-aggregate types, virtual functions may exist. Memory layout is uncertain, and is related to the compiler. Misuse of memory copies may cause serious problems.
+
+Even if a class of the aggregate type is directly copied and compared, and any functions hiding information or protecting data are destroyed, the `memcpy_s` and `memset_s` operations are not recommended.
+
+For details about the POD type, see the appendix.
+
+### Recommendation 9.1.2 Declare and initialize variables only when they are used.
+
+**Note**: It is a common low-level programming error that a variable is not assigned an initial value before being used. Declaring and initializing a variable just before using it will prevent this.
+
+If all variables are declared at the beginning of a function before they are used, their scope covers the entire function, which may lead to the following problems:
+* The program may become difficult to understand and maintain. The definition and use of variables are separated.
+* These variables are difficult to initialize properly. At the beginning of a function, there is often insufficient information for variable initialization, and a default null value (such as 0) is often assigned as the initial value. If a variable is used before it is assigned a valid value, it will also cause errors.
+
+Following the minimization principle of variable scopes and the principle of proximity declaration will make it easier to read code and understand variable types and initial values. In particular, use initialization to replace declaration and then assign values.
+
+```cpp
+// Bad example: Declaration is separated from initialization.
+string name; // The variable is not initialized in the declaration, and a default constructor is called.
+name = "zhangsan"; // An assignment operator is called again. Declaration is separate from definition, which is difficult to understand.
+
+// Good example: Declaration and initialization are together, and easy to understand.
+string name("zhangsan"); // Invoke a constructor.
+```
+
+
+## Expressions
+### Rule 9.2.1 A variable cannot be referenced again if it is contained in an increment or decrement operation in an expression.
+In an expression where the increment or decrement operations are performed on a variable, the variable cannot be referenced again. The result of a second referencing is not explicitly defined in C++ standards. The results in different compilers or different versions of a compiler may be different.
+Therefore, it is recommended that an undefined operation sequence not be assumed.
+
+Note that the problem of operation sequence cannot be solved by using parentheses because this is not a priority problem.
+
+Example:
+```cpp
+x = b[i] + i++; // Bad: Whether the position of b[i] is before or after the i++ is unclear.
+```
+The increment or decrement operation should be placed in a single line:
+```cpp
+x = b[i] + i;
+i++; // Good: i++ is placed in a single line.
+```
+
+Function parameter
+```cpp
+Func(i++, i); // Bad: Whether the increment operation happens for the second parameter is unclear
+```
+
+Good example:
+```cpp
+i++; // Good: i++ is placed in a single line.
+x = Func(i, i);
+```
+
+### Rule 9.2.2 A switch statement must have a default branch.
+In most cases, a switch statement requires a default branch to ensure that there is a default action when the case tag is missing for a processed value.
+
+Exception:
+If the switch condition variables are enumerated and the case branch covers all values, the default branch is redundant.
+Because modern compilers can check which case branches are missing in the switch statement and provide an advanced warning.
+
+```cpp
+enum Color {
+ RED = 0,
+ BLUE
+};
+
+// The switch condition variables are enumerated. Therefore, you do not need to add a default branch.
+switch (color) {
+ case RED:
+ DoRedThing();
+ break;
+ case BLUE:
+ DoBlueThing();
+ ...
+ break;
+}
+```
+
+### Recommendation 9.2.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged.
+When a variable is compared with a constant, placing the constant on the left, for example, if (MAX == v), does not comply with standard reading habits and is more difficult to understand.
+The constant should be placed on the right. The expression is written as follows:
+```cpp
+if (value == MAX) {
+
+}
+
+if (value < MAX) {
+
+}
+```
+There are special cases: for example, if the expression `if (MIN < value && value < MAX)` is used to describe a range, the first half, as a constant, should be placed on the left.
+
+You do not need to worry about writing '==' as '=' because a compilation alarm will be generated for `if (value = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable.
+
+### Recommendation 9.2.2 Use parentheses to specify the operator precedence.
+Use parentheses to specify the operator precedence. This will prevent program errors due to the inconsistency between default priority and the intended design. At the same time, it makes the code clearer and more readable. However, too many parentheses muddy the code, reducing readability. The following is a recommendation on their correct usage.
+
+- For binary and ternary operators, if multiple operators are involved, parentheses should be used.
+```cpp
+x = a + b + c; /* The operator does not change, and thus parentheses are not required. */
+x = Foo(a + b, c); /* The operator does not change, and thus parentheses are not required. */
+x = 1 << (2 + 3); /* More than one operator is used and thus parentheses are required. */
+x = a + (b / 5); /* More than one operator is used and thus parentheses are required. */
+x = (a == b) ? a : (a – b); /* More than one operator is used and thus parentheses are required. */
+```
+
+
+## Type Casting
+
+Do not use type branches to customize behaviors. Type branch customization behavior is prone to errors and is an obvious sign of attempting to compile C code using C++. This is very inflexible technology. If you forget to modify all branches when adding a new type to a compiler, you will not be notified. Use templates and virtual functions to let the type define itself rather than letting the calling side determine behavior.
+
+It is recommended that type casting be avoided. We should consider the data type in the code design instead of overusing type casting to solve type conflicts. When designing a basic type, consider the following:
+- Whether it is unsigned or signed.
+- Is it suitable for float or double?
+- Should you use int8, int16, int32, or int64 bit lengths?
+
+However, we cannot prohibit the use of type casting because the C++ language is a machine-oriented programming language, involving pointer addresses, and we interact with various third-party or underlying APIs. Their type design may not be reasonable and type casting tends to occur in the adaptation process.
+
+Exception: When calling a function, if we do not want to process the result of the function, first consider whether this is your best choice. If you do not want to process the return value of the function, cast it to void.
+
+### Rule 9.3.1 If type casting is required, use the type casting provided by the C++ instead of the C style.
+
+**Note**:
+
+The type casting provided by C++ is more targeted, easy to read, and more secure than the C style. C++ provides the following types of casting:
+- Type casting:
+1. `dynamic_cast`: Used to inherit the downstream transformation of the system. `dynamic_cast` has the type check function. Design the base class and derived class to avoid using dynamic_cast for casting.
+2. `static_cast`: Similar to the C style casting, which can be used to convert a value, or to convert the pointer or reference of a derived class into a base class pointer or reference. This casting is often used to eliminate type ambiguity brought on by multiple inheritance, which is relatively safe. If it is a pure arithmetic conversion, use the braces as stated in the following text.
+3. `reinterpret_cast`: Used to convert irrelevant types. `reinterpret_cast` forces the compiler to reinterpret the memory of a certain type of objects into another type, which is an unsafe conversion. It is recommended that `reinterpret_cast` be used as little as possible.
+4. `const_cast`: Used to remove the `const` attribute of an object so that the object can be modified. You are advised to use `const_cast` as little as possible.
+
+- Arithmetic conversion: (Supported by C++ 11 and later versions)
+ If the type information is not lost, for example, the casting from float to double, or from int32 to int64, the braces syntax is recommended.
+```cpp
+ double d{ someFloat };
+ int64_t i{ someInt32 };
+```
+
+### Recommendation 9.3.1 Avoid using `dynamic_cast`.
+1. `dynamic_cast` depends on the RTTI of C++ so that the programmer can identify the type of the object in C++ at run time.
+2. `dynamic_cast` indicates that a problem has occurred in the design of the base class and derived class.The derived class destroys the contract of the base class and it is necessary to use `dynamic_cast` to convert the class to a subclass for special processing. In this case, it is more desirable to improve the design of the class, instead of using `dynamic_cast` to solve the problem.
+
+### Recommendation 9.3.2 Avoid using `reinterpret_cast`.
+
+**Note**: `reinterpret_cast` is used to convert irrelevant types. Trying to use `reinterpret_cast` to force a type to another type destroys the security and reliability of the type and is an insecure casting method. Avoid casting between completely different types.
+
+### Recommendation 9.3.3 Avoid using `const_cast`.
+
+**Note**: The `const_cast` command is used to remove the `const` and `volatile` properties of an object.
+
+The action of using a pointer or reference after the const_cast conversion to modify the const property of an object is undefined.
+
+```cpp
+// Bad example:
+const int i = 1024;
+int* p = const_cast(&i);
+*p = 2048; // The action is undefined.
+```
+
+```cpp
+// Bad example:
+class Foo {
+public:
+ Foo() : i(3) {}
+
+ void Fun(int v)
+ {
+ i = v;
+ }
+
+private:
+ int i;
+};
+
+int main(void)
+{
+ const Foo f;
+ Foo* p = const_cast(&f);
+ p->Fun(8); // The action is undefined.
+}
+
+```
+
+
+## Resource Allocation and Release
+
+### Rule 9.4.1 When a single object is released, delete is used. When an array object is released, delete [] is used.
+Note: To delete a single object, use delete; to delete an array object, use delete []. The reasons are as follows:
+
+- new: Apply for memory from the system and call the corresponding constructor to initialize an object.
+- new[n]: Apply for memory for n objects and call the constructor n times for each object to initialize them.
+- delete: Call the corresponding destructor first and release the memory of an object.
+- delete[]: Call the corresponding destructor for each object and release their memory.
+
+If the usage of new and delete does not match this format, the results are unknown. For a non-class type, new and delete will not call the constructor or destructor.
+
+Bad example:
+```cpp
+const int MAX_ARRAY_SIZE = 100;
+int* numberArray = new int[MAX_ARRAY_SIZE];
+...
+delete numberArray;
+numberArray = NULL;
+```
+
+Good example:
+```cpp
+const int MAX_ARRAY_SIZE = 100;
+int* numberArray = new int[MAX_ARRAY_SIZE];
+...
+delete[] numberArray;
+numberArray = NULL;
+```
+
+### Recommendation 9.4.1 Use the RAII feature to trace dynamic allocation.
+
+Note: RAII is an acronym for Resource Acquisition Is Initialization. It is a simple technology that controls program resources (such as memory, file handle, network connections, and mutexes) by using the object lifecycle.
+
+The common practice is as follows: When the object is constructed, the resource is obtained, and the access to the resource is controlled so that the resource is always valid in the life cycle of the object. Finally, the resource is released when the object is destructed. This approach has two advantages:
+- We do not need to explicitly release resources.
+- The resources required by the object are always valid throughout the lifecycle of the object. This way, you do not need to check the validity of the resources, which simplifies logic and improves efficiency.
+
+
+In the following example, RAII removes the need for explicit release of mutex resources.
+
+```cpp
+class LockGuard {
+public:
+ LockGuard(const LockType& lockType): lock_(lockType)
+ {
+ lock_.Aquire();
+ }
+
+ ~LockGuard()
+ {
+ lock_.Relase();
+ }
+
+private:
+ LockType lock_;
+};
+
+
+bool Update()
+{
+ LockGuard lockGuard(mutex);
+ if (...) {
+ return false;
+ } else {
+ // Data operations
+ }
+
+ return true;
+}
+```
+
+## Standard Template Library
+
+The standard template library (STL) varies between products. The following table lists some basic rules and suggestions for each team.
+
+### Rule 9.5.1 Do not save the pointer returned by c_str () of std::string.
+
+Note: The C++ standard does not specify that the string::c_str () pointer is permanently valid. Therefore, the STL implementation used can return a temporary storage area and release it quickly when calling string::c_str (). Therefore, to ensure the portability of the program, do not save the result of string::c_str (). Instead, call it directly.
+
+Example:
+
+```cpp
+void Fun1()
+{
+ std::string name = "demo";
+ const char* text = name.c_str(); // After the expression ends, the life cycle of name is still in use and the pointer is valid.
+
+ // If a non-const member function (such as operator[] and begin()) of the string type is invoked and the string is modified,
+ // The text may become unavailable or may not be the original string.
+ name = "test";
+ name[1] = '2';
+
+ // When the text pointer is used next time, the string is no longer "demo".
+}
+
+void Fun2()
+{
+ std::string name = "demo";
+ std::string test = "test";
+ const char* text = (name + test).c_str(); // After the expression ends, the temporary object generated by the + operator may be destroyed, and the pointer may be invalid.
+
+ // When the text pointer is used next time, it no longer points to the valid memory space.
+}
+```
+Exception: In rare cases where high performance coding is required , you can temporarily save the pointer returned by string::c_str() to match the existing functions which support only the input parameters of the const char* type. However, you should ensure that the lifecycle of the string object is longer than that of the saved pointer, and that the string object is not modified within the lifecycle of the saved pointer.
+
+
+### Recommendation 9.5.1 Use std::string instead of char*.
+
+Note: Using string instead of `char*` has the following advantages:
+1. There is no need to consider the null character ’\0’at the end.
+2. You can directly use operators such as `+`, `=`, and `==`, and other character and string operation functions.
+3. There is no need to consider memory allocation operations.This helps avoid explicit usage of `new` and `delete` and the resulting errors.
+
+Note that in some STL implementations, string is based on the copy-on-write policy, which causes two problems. One is that the copy-on-write policy of some versions does not implement thread security, and the program breaks down in multi-threaded environments. Second, dangling pointers may be caused when a dynamic link library transfers the string based on the copy-on-write policy, due to the fact that reference count cannot be reduced when the library is unloaded. Therefore, it is important to select a reliable STL implementation to ensure the stability of the program.
+
+Exception:
+When an API of a system or other third-party library is called, only `char*` can be used for defined interfaces. However, before calling the interfaces, you can use string. When calling the interfaces, you can use `string::c_str()` to obtain the character pointer.
+When a character array is allocated as a buffer on the stack, you can directly define the character array without using string or containers such as `vector`.
+
+### Rule 9.5.2 Do not use auto_ptr.
+Note: The `std::auto_ptr` in the STL library has an implicit ownership transfer behavior. The code is as follows:
+```cpp
+auto_ptr p1(new T);
+auto_ptr p2 = p1;
+```
+After the second line of statements is executed, p1 does not point to the object allocated in line 1 and becomes `NULL`. Therefore, `auto_ptr` cannot be placed in any standard containers.
+This ownership transfer behavior is not expected. In scenarios where ownership must be transferred, implicit transfer should not be used. This often requires the programmer to keep extra attention on code that uses `auto_ptr`, otherwise access to a null pointer will occur.
+There are two common scenarios for using auto_ptr . One is to transfer it as a smart pointer to outside the function that generates the auto_ptr , and the other is to use auto_ptr as the RAII management class. Resources are automatically released when the lifecycle of auto_ptr expires.
+In the first scenario, you can use std::shared_ptr instead.
+In the second scenario, you can use std::unique_ptr in the C++ 11 standard. std::unique_ptr is a substitute for std::auto_ptr and supports explicit ownership transfer.
+
+Exception:
+Before the C++ 11 standard is widely used, std::auto_ptr can be used in scenarios where ownership needs to be transferred. However, it is recommended that std::auto_ptr be encapsulated. The copy constructor and assignment operator of the encapsulation class should not be used in a standard container.
+
+
+### Recommendation 9.5.2 Use the new standard header files.
+
+Note:
+When using the standard header file of C++, use `` instead of ``.
+
+## Usage of const
+Add the keyword const before the declared variable or parameter (example: `const int foo`) to prevent the variable from being tampered with. Add the const qualifier to the function in the class (example: `class Foo {int Bar (char c) const;} ;`) to make sure the function does not modify the status of the class member variable. const variables, data members, functions, and parameters ensure that the type detection during compilation is accurate and errors are found as soon as possible. Therefore, we strongly recommend that const be used in any possible case.
+Sometimes it is better to use constexpr from C++ 11 to define real constants.
+
+### Rule 9.6.1 For formal parameters of pointer and reference types, if the parameters do not need to be modified, use const.
+Unchanging values are easier to understand, trace, and analyze. `const` is used as the default option and is checked during compilation to make the code more secure and reliable.
+```cpp
+class Foo;
+
+void PrintFoo(const Foo& foo);
+```
+
+### Rule 9.6.2 For member functions that do not modify member variables, use const.
+Declare the member function as `const` whenever possible. The access function should always be const. So long as the function of a member is not modified, the function is declared with const.
+When you need to modify data members in a virtual function, take all classes in the inheritance chain into account instead of only focusing on the implementation of a single class.
+```cpp
+class Foo {
+public:
+
+ // ...
+
+ int PrintValue() const // const modifies member functions and does not modify member variables.
+ {
+ std::cout << value_ << std::endl;
+ }
+
+ int GetValue() const // const modifies member functions and does not modify member variables.
+ {
+ return value_;
+ }
+
+private:
+ int value_;
+};
+```
+
+### Recommendation 9.6.1 Member variables that will not be modified after initialization should be defined as constants.
+
+```cpp
+class Foo {
+public:
+ Foo(int length) : dataLength_(length) {}
+private:
+ const int dataLength_;
+};
+```
+
+## Exceptions
+
+### Recommendation 9.7.1 If the function does not throw an exception, the declaration is `noexcept`.
+**Reasons:**
+1. If the function does not throw an exception, the declaration is `noexcept`, which enables the compiler to optimize the function to the maximum extent, for example, reducing the execution paths and improving the efficiency of exiting when an error occurs.
+2. For STL containers such as `vector`, to ensure the interface robustness, if the `move ` constructor of saved items is not declared as `noexcept`, the `copy machanism` instead of the `move machanism` is used when the items are removed from the container. This would cause performance loss risks. If the function does not throw an exception, or a program does not intercept and process an exception thrown by the function, new `noexcept` keywords can be used to modify the function, indicating that the function does not throw an exception or the thrown exception is not intercepted or processed. For example:
+
+```cpp
+extern "C" double sqrt(double) noexcept; // No exceptions are thrown.
+
+// noexcept can still be used when exceptions may be thrown.
+// The exception of memory exhaustion is not processed. The function is simply declared as noexcept.
+std::vector MyComputation(const std::vector& v) noexcept
+{
+ std::vector res = v; // Exceptions may be thrown.
+ // do something
+ return res;
+}
+```
+
+**Example:**
+
+```cpp
+RetType Function(Type params) noexcept; // Maximized optimization
+RetType Function(Type params) noexcept; // No optimization
+
+// Declaration as noexcept for the move operation of std::vector is needed.
+class Foo1 {
+public:
+ Foo1(Foo1&& other); // no noexcept
+};
+
+std::vector a1;
+a1.push_back(Foo1());
+a1.push_back(Foo1()); // The copy constructor is called to enable the container expansion and removal of existing items.
+
+class Foo2 {
+public:
+ Foo2(Foo2&& other) noexcept;
+};
+
+std::vector a2;
+a2.push_back(Foo2());
+a2.push_back(Foo2()); //Triggers container expansion and invokes the move constructor to move existing elements.
+```
+
+**Note**
+The default constructor, destructor, `swap` function, and `move` operator should not throw an exception.
+
+## Templates
+
+Template programming allows for extremely flexible interfaces that are type safe and high performance, enabling reuse of code of different types but with the same behavior.
+
+The disadvantages of template proramming are as follows:
+
+1. The techniques used in template programming are often obscure to anyone but language experts. Code that uses templates in complicated ways is often unreadable, and is hard to debug or maintain.
+2. Template programming often leads to extremely poor compiler time error messages: even if an interface is simple, complicated implementation details become visible when the user does something wrong.
+3. If the template is not properly used, the code will be over expanded during runtime.
+4. It is difficult to modify or refactor template code. The template code is expanded in multiple contexts, and it is hard to verify that the transformation makes sense in all of them.
+
+Therefore, it is recommended that __ template programming be used only in a small number of basic components and basic data structure__. When using the template programming, minimize the __ complexity as much as possible, and __ avoid exposing the template__. It is better to hide programming as an implementation detail whenever possible, so that user-facing headers are readable. And you should write sufficiently detailed comments for code that uses templates.
+
+
+## Macros
+In the C++ language, it is strongly recommended that complex macros be used as little as possible.
+- For constant definitions, use `const` or `enum` as stated in the preceding sections.
+- For macro functions, try to be as simple as possible, comply with the following principles, and use inline functions and template functions for replacement.
+
+```cpp
+// The macro function is not recommended.
+#define SQUARE(a, b) ((a) * (b))
+
+// Use the template function and inline function as a replacement.
+template T Square(T a, T b) { return a * b; }
+```
+
+For details about how to use macros, see the related chapters about the C language specifications.
+**Exception**: For some common and mature applications, for example, encapsulation for new and delete, the use of macros can be retained.
+
+# 10 Modern C++ Features
+
+As the ISO released the C++ 11 language standard in 2011 and released the C++ 17 in March 2017, the modern C++ (C++ 11/14/17) adds a large number of new language features and standard libraries that improve programming efficiency and code quality.
+This chapter describes some guidelines for modern C++ use, to avoid language pitfalls.
+
+## Code Simplicity and Security Improvement
+### Recommendation 10.1.1 Use `auto` properly.
+**Reasons**
+
+* `auto` can help you avoid writing verbose, repeated type names, and can also ensure initialization when variables are defined.
+* The `auto` type deduction rules are complex and need to be read carefully.
+* If using `auto` makes the code clearer, use a specific type of it and use it only for local variables.
+
+**Example**
+
+```cpp
+// Avoid verbose type names.
+std::map::iterator iter = m.find(val);
+auto iter = m.find(val);
+
+// Avoid duplicate type names.
+class Foo {...};
+Foo* p = new Foo;
+auto p = new Foo;
+
+// Ensure that the initialization is successful.
+int x; // The compilation is correct but the variable is not initialized.
+auto x; // The compilation failed. Initialization is needed.
+```
+
+`auto` type deduction may cause the following problems:
+
+```cpp
+auto a = 3; // int
+const auto ca = a; // const int
+const auto& ra = a; // const int&
+auto aa = ca; // int, const and reference are neglected.
+auto ila1 = { 10 }; // std::initializer_list
+auto ila2{ 10 }; // std::initializer_list
+
+auto&& ura1 = x; // int&
+auto&& ura2 = ca; // const int&
+auto&& ura3 = 10; // int&&
+
+const int b[10];
+auto arr1 = b; // const int*
+auto& arr2 = b; // const int(&)[10]
+```
+
+If you do not pay attention to `auto` type deduction and ignore the reference, hard-to-find performance problems may be created.
+
+```cpp
+std::vector v;
+auto s1 = v[0]; // auto deduction changes s1 to std::string in order to copy v[0].
+```
+
+If `auto` is used to define an interface, such as a constant in a header file, the type may be changed if the developer has modified the value.
+
+### Rule 10.1.1 Use the keyword `override` when rewriting virtual functions.
+**Reason:**
+The keyword `override` ensures that the function is a virtual function and an overridden virtual function of the base class. If the subclass function is different from the base class function prototype, a compilation alarm is generated. `final` also ensures that virtual functions are not overridden by subclasses.
+
+If you modify the prototype of a base class virtual function but forget to modify the virtual function overridden by the subclass, you can find inconsistency during compilation. You can also avoid forgetting to modify the overridden function when there are multiple subclasses.
+
+**Example**
+
+```cpp
+class Base {
+public:
+ virtual void Foo();
+ virtual void Foo(int var);
+ void Bar();
+};
+
+class Derived : public Base {
+public:
+ void Foo() const override; // Compilation failed: derived::Foo is different from that of the prototype of base::Foo and is not overridden.
+ void Foo() override; // Compilation successful: derived::Foo overrode base::Foo.
+ void Foo(int var) final; // Compilation successful: Derived::Foo(int) rewrites Base::Foo(int), and the derived class of Derived cannot override this function.
+ void Bar() override; // Compilation failed: base::Bar is not a virtual function.
+};
+```
+
+**Summary**
+1. When defining the virtual function for the first time based on the base class, use the keyword `virtual`.
+2. When overriding the virtual function by a subclass in a base class, including destructors, use the keyword `override` or `final` instead of `virtual`.
+3. For the non-virtual function, do not use `virtual` or `override`.
+
+### Rule: 10.1.2 Use the keyword `delete` to delete functions.
+**Reason**
+The `delete` keyword is clearer and the application scope is wider than a class member function that is declared as private and not implemented.
+
+**Example:**
+
+```cpp
+class Foo {
+private:
+ // Whether the copy structure is deleted or not is unknown because usually only the header file is checked.
+ Foo(const Foo&);
+};
+
+class Foo {
+public:
+ // Explicitly delete the copy assignment operator.
+ Foo& operator=(const Foo&) = delete;
+};
+```
+
+The `delete` keyword can also be used to delete non-member functions.
+
+```cpp
+template
+void Process(T value);
+
+template<>
+void Process(void) = delete;
+```
+
+### Rule 10.1.3 Use `nullptr` instead of `NULL` or `0`.
+**Reason:**
+For a long time, C++ has not had a keyword that represents a null pointer, which is embarrassing:
+
+```cpp
+#define NULL ((void *)0)
+
+char* str = NULL; // Error: void* cannot be automatically converted to char*.
+
+void(C::*pmf)() = &C::Func;
+if (pmf == NULL) {} // Error: void* cannot be automatically converted to the pointer that points to the member function.
+```
+
+If `NULL` is defined as `0` or `0L`, the above problems can be solved.
+
+Alternatively, use `0` directly in places where null pointers are required. However, another problem occurs. The code is not clear, especially when `auto` is used for automatic deduction.
+
+```cpp
+auto result = Find(id);
+if (result == 0) { // Does Find() return a pointer or an integer?
+ // do something
+}
+```
+
+Literally `0` is of the `int` type (`0L` is the `long` type). Therefore, neither `NULL` nor `0` is a pointer type.
+When a function of the pointer or integer type is overloaded, `NULL` or `0` calls only the overloaded pointer function.
+
+```cpp
+void F(int);
+void F(int*);
+
+F(0); // Call F(int) instead of F(int*).
+F(NULL); // Call F(int) instead of F(int*).
+```
+
+In addition, `sizeof(NULL) == sizeof(void*)` does not always make sense, which is a potential risk.
+
+Summary: If `0` or `0L` is directly used, the code is not clear and type security cannot be ensured. If `NULL` is used, the type security cannot be ensured. These are all potential risks.
+
+`nullptr` has many advantages. It literally represents the null pointer and makes the code clearer. More to the point, it is no longer an integer type.
+
+`nullptr` is of the `std::nullptr_t` type. `std::nullptr_t` can be implicitly converted into all original pointer types, so that `nullptr` can represent a null pointer that points to any type.
+
+```cpp
+void F(int);
+void F(int*);
+F(nullptr); // Call F(int*).
+
+auto result = Find(id);
+if (result == nullptr) { // Find() returns a pointer.
+ // do something
+}
+```
+
+### Rule 10.1.4 Use `using` instead of `typedef`.
+For versions earlier than `C++11`, you can define the alias of the type by using `typedef`. No one wants to repeat code like `std::map>`.
+
+```cpp
+typedef std::map> SomeType;
+```
+
+Using alias for the type is actually encapsulating the type. This encapsulation makes the code clearer, and to a large extent avoids the bulk modification caused by the type change.
+For versions supporting C++ 11 features, `using` is provided to implement `alias declarations`:
+
+```cpp
+using SomeType = std::map>;
+```
+
+Compare the two formats:
+
+```cpp
+typedef Type Alias; // It cannot be told whether the original Type or Alias is at the front.
+using Alias = Type; // The format confirms to the assignment rule. It is easy to understand and helps reduce errors.
+```
+
+If this is not enough to prove the advantages of `using`, the alias template may be a better example:
+
+```cpp
+//: Only one line of code is need to define an alias for a template.
+template
+using MyAllocatorVector = std::vector>;
+
+MyAllocatorVector data; // An alias for a template defined with "using".
+
+template
+class MyClass {
+private:
+ MyAllocatorVector data_; // Another.
+};
+```
+
+`typedef` does not support alias templates and they have to be hacked in.
+
+```cpp
+// A template is used for packaging typedef. Therefore, a template class is needed.
+template
+struct MyAllocatorVector {
+ typedef std::vector> type;
+};
+
+MyAllocatorVector::type data; // ::type needs to be added when using typedef to define an alias.
+
+template
+class MyClass {
+private:
+ typename MyAllocatorVector::type data_; // For a template class, typename is also needed in addition to ::type.
+};
+```
+
+### Rule 10.1.5 Do not use std::move to operate the const object.
+Literally, `std::move` means moving an object. The const object cannot be modified and cannot be moved. Therefore, using `std::move` to operate the const object may confuse code readers.
+Regarding actual functions, `std::move` converts an object to the rvalue reference type. It can convert the const object to the rvalue reference of const. Because few types define the move constructor and the move assignment operator that use the const rvalue reference as the parameter, the actual function of code is often degraded to object copy instead of object movement, which brings performance loss.
+
+**Bad example:**
+```cpp
+std::string g_string;
+std::vector g_stringList;
+
+void func()
+{
+ const std::string myString = "String content";
+ g_string = std::move(myString); // Bad: myString is not moved. Instead, it is copied.
+ const std::string anotherString = "Another string content";
+ g_stringList.push_back(std::move(anotherString)); // Bad: anotherString is not moved. Instead, it is copied.
+}
+```
+
+## Smart Pointers
+### Rule 10.2.1 Use smart pointers instead of a raw pointer to manage resources.
+**Reason:**
+Avoid resource leakage.
+
+**Example:**
+
+```cpp
+void Use(int i)
+{
+ auto p = new int {7}; // Bad: Initializing local pointers with new.
+ auto q = std::make_unique(9); // Good: Guarantee that memory is released.
+ if (i > 0) {
+ return; // Return and possible leak.
+ }
+ delete p; // Too late to salvage.
+}
+```
+
+**Exception:**
+Raw pointers can be used in scenarios requiring high performance and compatibility.
+
+### Rule 10.2.2 Use `unique_ptr` instead of `shared_ptr`.
+**Reasons:**
+1. Using `shared_ptr` a lot has an overhead (atomic operations on the `shared_ptr`s reference count have a measurable cost).
+2. Shared ownership in some cases (such as circular dependency) may create objects that can never be released.
+3. Shared ownership can be an attractive alternative to careful ownership design but it may obfuscate the design of a system.
+
+### Rule 10.2.3 Use `std::make_unique` instead of `new` to create a `unique_ptr`.
+**Reasons:**
+1. `make_unique` provides a simpler creation method.
+2. `make_unique` ensures the exception safety of complex expressions.
+
+**Example:**
+
+```cpp
+// Bad: MyClass appears twice, which carries a risk of inconsistency.
+std::unique_ptr ptr(new MyClass(0, 1));
+// Good: MyClass appears once and there is no possibility of inconsistency.
+auto ptr = std::make_unique(0, 1);
+```
+
+Recurrence of types may cause serious problems, and it is difficult to find them:
+
+```cpp
+// The code compiles fine, but new and delete usage does not match.
+std::unique_ptr ptr(new uint8_t[10]);
+std::unique_ptr ptr(new uint8_t);
+// No exception safety: The compiler may calculate parameters in the following order:
+// 1. Allocate the memory of Foo.
+// 2. Construct Foo.
+// 3. Call Bar.
+// 4. Construct unique_ptr.
+// If Bar throws an exception, Foo is not destroyed and a memory leak occurs.
+F(unique_ptr(new Foo()), Bar());
+
+// Exception safety: Calling of function is not interrupted.
+F(make_unique(), Bar());
+```
+
+**Exception:**
+`std::make_unique` does not support user-defined `deleter`.
+In the scenario where the `deleter` needs to be customized, it is recommended that `make_unique` be implemented in the customized version’s own namespace.
+Using `new` to create `unique_ptr` with the user-defined `deleter` is the last choice.
+
+### Rule 10.2.4 Create `shared_ptr` by using `std::make_shared` instead of `new`.
+**Reason:**
+In addition to the consistency factor similar to that in `std::make_unique` when using `std::make_shared`, performance is also a factor to consider.
+`std::shared_ptr` manages two entities:
+* Control block (storing reference count, `deleter`, etc.)
+* Managed objects
+
+When `std::make_shared` creates `std::shared_ptr`, it allocates sufficient memory for storing control blocks and managed objects on the heap at a time. When `std::shared_ptr(new MyClass)`is used to create a `std::shared_ptr`, not only does `new MyClass` trigger heap allocation, but the constructor function of `std::shard_ptr` triggers a second heap allocation, resulting in extra overhead.
+
+**Exception:**
+Similar to `std::make_unique`, `std::make_shared` does not support `deleter` customization.
+
+## Lambda
+### Recommendation 10.3.1 Use `lambda` to capture local variables or write local functions when normal functions do not work.
+**Reason:**
+Functions cannot capture local variables or be declared at local scope. If you need those things, choose `lambda` instead of handwritten `functor`.
+On the other hand, `lambda` and `functor` objects do not support overloading. If overloading is required, use a function.
+If both `lambda` and functions work, a function is preferred. Use the simplest tool.
+
+**Example:**
+
+```cpp
+// Write a function that accepts only an int or string.
+// -- Overloading is more natural.
+void F(int);
+void F(const string&);
+
+// The local state needs to be captured or appear in the statement or expression range.
+// -- A lambda is more natural.
+vector v = LotsOfWork();
+for (int taskNum = 0; taskNum < max; ++taskNum) {
+ pool.Run([=, &v] {...});
+}
+pool.Join();
+```
+
+### Rule 10.3.1 Avoid capturing by reference in lambdas that will not be used locally.
+**Reason:**
+Using `lambdas` at a "nonlocal" scope includes returning, storing on the heap, and passing to another thread. Local pointers and references should not outlive their scope. Capturing by reference in `lambdas` indicates storing a reference to a local object. If this leads to a reference that exceeds the lifecycle of a local variable, capturing by reference should not be used.
+
+**Example:**
+
+```cpp
+// Bad
+void Foo()
+{
+ int local = 42;
+ // Capture a reference to a local variable.
+ // After the function returns results, local no longer exists,
+ // Process() call will have undefined behavior.
+ threadPool.QueueWork([&]{ Process(local); });
+}
+
+// Good
+void Foo()
+{
+ int local = 42;
+ // Capture a copy of local.
+ // Since a copy of local is made, it will be always available for the call.
+ threadPool.QueueWork([=]{ Process(local); });
+}
+```
+
+### Recommendation 10.3.2 All variables are explicitly captured if `this` is captured.
+**Reason:**
+The `[=]` in the member function seems to indicate capturing by value but actually it is capturing data members by reference because it captures the invisible `this` pointer by value. Generally, it is recommended that capturing by reference be avoided. If it is necessary to do so, write `this` explicitly.
+
+**Example:**
+
+```cpp
+class MyClass {
+public:
+ void Foo()
+ {
+ int i = 0;
+
+ auto Lambda = [=]() { Use(i, data_); }; // Bad: It looks like we are copying or capturing by value but member variables are actually captured by reference.
+
+ data_ = 42;
+ Lambda(); // Call use(42);
+ data_ = 43;
+ Lambda(); // Call use(43);
+
+ auto Lambda2 = [i, this]() { Use(i, data_); }; // Good: the most explicit and least confusing method.
+ }
+
+private:
+ int data_ = 0;
+};
+```
+
+### Recommendation 10.3.3 Avoid default capture modes.
+**Reason:**
+The lambda expression provides two default capture modes: by-reference (&) and by-value (=).
+By default, the "by-reference" capture mode will implicitly capture the reference of all local variables, which will easily lead to dangling references. By contrast, explicitly writing variables that need to be captured can make it easier to check the lifecycle of an object and reduce the possibility of making a mistake.
+By default, the "by-value” capture mode will implicitly capture this pointer, and it is difficult to find out which variables the lambda function depends on. If a static variable exists, the reader mistakenly considers that the lambda has copied a static variable.
+Therefore, it is required to clearly state the variables that lambda needs to capture, instead of using the default capture mode.
+
+**Bad example:**
+```cpp
+auto func()
+{
+ int addend = 5;
+ static int baseValue = 3;
+
+ return [=]() { // Only addend is actually copied.
+ ++baseValue; // The modification will affect the value of the static variable.
+ return baseValue + addend;
+ };
+}
+```
+
+**Good example:**
+```cpp
+auto func()
+{
+ int addend = 5;
+ static int baseValue = 3;
+
+ return [addend, baseValue = baseValue]() mutable { // Uses the C++14 capture initialization to copy a variable.
+ ++baseValue; // Modifying the copy of a static variable does not affect the value of the static variable.
+ return baseValue + addend;
+ };
+}
+```
+
+Reference: Effective Modern C++: Item 31: Avoid default capture modes.
+
+## Interfaces
+### Recommendation 10.4.1 Use `T*` or `T&` arguments instead of a smart pointer in scenarios where ownership is not involved.
+**Reasons:**
+1. Passing a smart pointer to transfer or share ownership should only be used when the ownership mechanism is explicitly required.
+2. Passing a smart pointer (for example, passing the `this` smart pointer) restricts the use of a function to callers using smart pointers.
+3. Passing a shared smart pointer adds a runtime performance cost.
+
+**Example:**
+
+```cpp
+// Accept any int*.
+void F(int*);
+
+// Accept only integers for which you want to transfer ownership.
+void G(unique_ptr);
+
+// Accept only integers for which you want to share ownership.
+void G(shared_ptr);
+
+// Does not need to change the ownership but requires ownership of the caller.
+void H(const unique_ptr&);
+
+// Accept any int.
+void H(int&);
+
+// Bad
+void F(shared_ptr& w)
+{
+ // ...
+ Use(*w); // When only w is used, lifecycle management is not required.
+ // ...
+};
+```
+
diff --git a/docs-en/get-code/source-code-acquisition.md b/docs-en/get-code/source-code-acquisition.md
index 521b65baad6c6ea749403f604d339a92db82b77c..01991e60354aeb6a83fe881d5fc110911d28e301 100755
--- a/docs-en/get-code/source-code-acquisition.md
+++ b/docs-en/get-code/source-code-acquisition.md
@@ -47,7 +47,7 @@ You can download the source code or the corresponding solutions from the image l
@@ -234,7 +234,7 @@ Add the bundle \(**@ohos/demo** as an example\) to your project as follows:
Method 1 \(recommended\): Use the **repo** tool to download source code.
```
-repo init -u https://gitee.com/openharmony/manifest.git -b master
+repo init -u https://gitee.com/openharmony/manifest.git -b master --no-repo-verify
repo sync -c
```
diff --git a/docs-en/get-code/tool-acquisition.md b/docs-en/get-code/tool-acquisition.md
index 90ed477644c39785b999bd1112b1a638967af480..1b79636ece91988d11c9e4fbf5ea6c3584fa83ed 100755
--- a/docs-en/get-code/tool-acquisition.md
+++ b/docs-en/get-code/tool-acquisition.md
@@ -2,64 +2,76 @@
## Acquiring Compilation Toolchain
-Download the compilation toolchain from image sites listed in the following table. For details about how to install the compilation toolchain, see the **Environment Setup** section in **Getting Started** of the specific development guide.
+The following table lists the compilation toolchain downloaded from an image site. For details about how to download and install all compilation tools, see the **Environment Setup** section in **Getting Started** of the specific development board.
**Table 1** Acquiring compilation toolchain
-
@@ -98,7 +110,7 @@ HUAWEI DevEco Device Tool \(DevEco Device Tool for short\) is a one-stop integra
## Tool Introduction
-HUAWEI DevEco Studio \(DevEco Studio for short\) is a one-stop IDE oriented to OpenHarmony-based devices in all scenarios. It allows you to create project templates, and develop, build, debug, and release OpenHarmony applications from end to end. DevEco Studio enables you to efficiently develop applications with OpenHarmony distributed capabilities, thereby empowering you to innovate applications.
+HUAWEI DevEco Studio \(DevEco Studio for short\) is a one-stop IDE oriented to Huawei devices in all scenarios. It allows you to create project templates, and develop, build, debug, and release OpenHarmony applications from end to end. DevEco Studio enables you to efficiently develop applications with OpenHarmony distributed capabilities, thereby empowering you to innovate applications.
## Website
diff --git a/docs-en/guide/Readme-EN.md b/docs-en/guide/Readme-EN.md
old mode 100755
new mode 100644
diff --git a/docs-en/guide/adding-pages-4.md b/docs-en/guide/adding-pages-4.md
deleted file mode 100755
index a9426b25c99ae8e7c1fa0dc64378e8590431e36c..0000000000000000000000000000000000000000
--- a/docs-en/guide/adding-pages-4.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Adding Pages
-
-## Creating the Home Page \(Creating a Project\)
-
-After the project is created, the **index** page is generated by default. The following figure shows the project directory.
-
-**Figure 1** Project directory
-![](figures/project-directory-1.png "project-directory-1")
-
-## Creating Detail and History Pages
-
-Perform the following steps twice to create the rest two pages:
-
-1. Right-click **pages** and choose **New** \> **JS Page** from the shortcut menu.
-
- **Figure 2** Adding a page
- ![](figures/adding-a-page-2.png "adding-a-page-2")
-
-2. Enter the page name.
-
- **Figure 3** Entering the page name
- ![](figures/entering-the-page-name-3.png "entering-the-page-name-3")
-
-3. Confirm the creation.
-
- The following figure shows the application project directory after the **detail** page and **history** page are created. Each page contains a **.hml** layout file, a **.css** file, and a **.js** file \(containing service logic code\).
-
- **Figure 4** Complete project directory
- ![](figures/complete-project-directory-4.png "complete-project-directory-4")
-
-
diff --git a/docs-en/guide/adding-pages.md b/docs-en/guide/adding-pages.md
old mode 100755
new mode 100644
diff --git a/docs-en/guide/building-the-detail-page-6.md b/docs-en/guide/building-the-detail-page-6.md
deleted file mode 100755
index 073539f91faae7de1266f2cd814c62ad1ecd23dd..0000000000000000000000000000000000000000
--- a/docs-en/guide/building-the-detail-page-6.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Building the Detail Page
-
-The **detail** page displays air quality data, such as CO, NO2, PM10, PM2.5, and SO2. Use multiple **** components to display the information, and use the **** component to continuously swipe up and down on the page. Note that **** can have multiple child components, which must be ****. For the **detail** page, you need to develop for the page typesetting and styles. The detailed code is as follows:
-
-## detail.hml
-
-```
-
-
-
-
-
-```
-
-## detail.css
-
-```
-.line-div{
- background-color:#f5fffa;
- height:2px;
- width:454px;
-}
-.info-div-width-height{
- width:321px;
- height:60px;
- margin-top: 20px;
-}
-.gas-name{
- color:#f5fffa;
- width:160px;
- height:30px;
-}
-.gas-value{
- text-align:right;
- color:#00fa9a;
- width:160px;
- height:30px;
-}
-.config-info {
- height:40px;
- width:321px;
- color:#f5fffa;
-}
-```
-
-## detail.js
-
-```
-import router from '@system.router'
-export default {
- data:{// Initialization information
- location:"HangZhou",
- udpateStatus:"1h ago",
- dataSource:"tianqi.com",
- updateTime:"15:13",
- updated:'Updated',
- dataSourceName:'Data Source',
- sampledOn:'Sampled on',
- cityIndex:0,
- airData:['100', '90', '120', '50', '150', '40', '25']
- },
- onInit(){
- // Process information in multiple languages.
- this.location = this.$t(this.location);
- this.updated = this.$t("updated");
- this.dataSourceName = this.$t("dataSourceName");
- this.sampledOn = this.$t("sampledOn");
- this.monitoringStation = this.$t("monitoringStation");
- if(this.selectedCityIndex != null){ // Save city information sent from the home page.
- this.cityIndex= this.selectedCityIndex;
- }
- },
- openHistroy(){// Switch to the history page.
- router.replace({
- uri:'pages/history/history'
- });
- },
- backMain(){ // Go back to the home page and return the information about the selected city.
- router.replace({
- uri:'pages/index/index',
- params:{selectedCityIndex:this.cityIndex}
- });
- }
-}
-```
-
diff --git a/docs-en/guide/building-the-detail-page.md b/docs-en/guide/building-the-detail-page.md
old mode 100755
new mode 100644
diff --git a/docs-en/guide/building-the-history-page-7.md b/docs-en/guide/building-the-history-page-7.md
deleted file mode 100755
index bfafd5640717815416dc14a12ba18181dc744d3f..0000000000000000000000000000000000000000
--- a/docs-en/guide/building-the-history-page-7.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# Building the History Page
-
-The **history** page displays the air quality data of a week in a chart. On this page, multiple **
** components are used to replace the **** component to display the chart. The sample code is as follows:
-
-## history.hml
-
-```
-
-
-
- {{historicalData}}
-
-
-
-
-
-
-
- {{$item}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-```
-
-## history.css
-
-```
-.div-info-location{
- color:#dcdcdc;
- width:321px;
- height:40px;
-}
-.div-info-historical-data{
- color:#f5fffa;
- width:321px;
- height:40px;
-}
-.gas-name{
- color:#f0ffff;
- text-align:right;
- width:321px;
- height:32px;
-}
-.info-list-item{
- width:321px;
- height:80px;
-}
-```
-
-## history.js
-
-```
-import router from '@system.router'
-module.exports = {
- data: {
- historicalData:"historicalData",
- datasets:["CO","O3","NO2","NO","PM25","SO2"]
- },
- onInit(){
- // Process information in multiple languages.
- this.historicalData = this.$t(this.historicalData);
- },
- backDetail(){
- router.replace({ // Return to the detail page.
- uri:'pages/detail/detail'
- });
- }
-}
-```
-
diff --git a/docs-en/guide/building-the-history-page.md b/docs-en/guide/building-the-history-page.md
old mode 100755
new mode 100644
diff --git a/docs-en/guide/building-the-home-page-5.md b/docs-en/guide/building-the-home-page-5.md
deleted file mode 100755
index 146298be5cba629bac28e74486a8a543ad24e064..0000000000000000000000000000000000000000
--- a/docs-en/guide/building-the-home-page-5.md
+++ /dev/null
@@ -1,271 +0,0 @@
-# Building the Home Page
-
-The application home page displays air quality information of the current city. There are two screens on the home page. Each screen displays the air quality information of a city, including the AQI and city name. The AQI value can be displayed in the form of a ring progress bar with animation.
-
-1. The **** component is required to implement switching between the two screens.
-
- Add a root **** to the **.hml** file. Note that each **.hml** file can contain only one root component. The code snippet is as follows:
-
- ```
-
-
- ```
-
- - **class="container"** indicates the style used by the component. The **container** is a style class in the **index.css** file. The code snippet is as follows:
-
- ```
- .container{
- height: 454px;
- width: 454px;
- }
- ```
-
- This style class sets the height and width of the component. For device development, the component height and width must be explicitly specified. Otherwise, the component may fail to be displayed.
-
-
- - **index="\{\{swiperPage\}\}" duration="500" onchange="swiperChange"** sets the component attribute and event. **duration="500"** indicates that the duration of the swiping animation is 500 ms.
- - **index="\{\{swiperPage\}\}"** specifies the index of the child component of ****. **\{\{swiperPage\}\}** indicates that the index value is dynamically bound to the **swiperPage** variable in the JavaScript code. The index value changes with the **swiperPage** value.
- - **onchange="swiperChange"** binds the change event of the **** component to the **swiperChange** function. The JavaScript code is as follows:
-
- ```
- // Import the router module for page switching.
- import router from '@system.router'
- export default {
- // Define parameters.
- data: {
- swiperPage:0 // The first page is displayed by default.
- },
- onInit () {
- },
- // Swiping event, which saves the index value of the current . The index value is saved to the swiperPage variable each time a swiping occurs.
- swiperChange (e) {
- this.swiperPage = e.index;
- }
- }
- ```
-
-
-2. Set the information about each city to be displayed on a screen. In each screen, four types of information needs to be displayed using different components.
-
- Add two child components \(****\) to the ****. Add the ****, ****, and **