C language code specification

Source: Internet
Author: User

1. Basic Requirements
1.1 program structure analysis, easy to understand, the number of program lines of a single function cannot exceed 100.
1.2 What are you going to do? It should be simple, straightforward, and code should be streamlined to avoid spam.
1.3 try to use standard library functions and public functions.
1.4 do not define global variables at will. Use local variables whenever possible.
1.5 use parentheses to avoid ambiguity.
2. Readability requirements
2.1 readability first, efficiency second.
2.2 keep the comments exactly the same as the code.
2.3 Each source program file has a description of the file header. For details about the specifications, see the specifications.
2.4 each function has a description of the function header. For details about the specifications, see the specifications.
2.5 comments can reflect the meaning of a major variable (structure, union, class, or object) when defining or referencing it.
2.7 DEFINE a constant.
2.8 each stage of the processing process is annotated.
2.9 annotations are provided before typical algorithms.
2.10 use indentation to display the logical structure of the program. The indentation quantity is consistent and the unit is the Tab key. 6 tabs are defined.
Bytes.
2.11 The number of cycles and branches must not exceed five layers.
2.12 comments can be in the same line as the statement or in the upstream.
2.13 empty lines and white spaces are also special comments.
2.14 clear statements without comments.
2.15 The scope of comments can be definition, reference, condition branch, and a piece of code.
2.16 The number of comments (excluding program headers and function headers) accounts for 1/5 to 1/3 of the total number of lines.
3. Structured requirements
3.1 two equivalent branches are prohibited.
3.2 disable the GOTO statement.
3.3 Use the IF statement to emphasize that only one of the two groups of statements is executed. Disable else goto and else return.
3.4 use CASE to implement multiple branches.
3.5 avoid multiple exits from the loop.
The 3.6 function has only one exit.
3.7 The conditional assignment statement is not used.
3.8 avoid unnecessary branches.
3.9 do not replace logical expressions with conditional branches.
4. correctness and fault tolerance requirements
4.1 programs are correct first, followed by beautiful
4.2 it cannot be proved that your program is not wrong. Therefore, after writing a program, you should check it back.
4.3 A new error may occur when an error is changed. Therefore, the impact on other programs should be considered before modification.
4.4 all variables must be initialized before being called.
4.5 all user input must be checked for validity.
4.6 do not compare equal floating point numbers,
For example: 10.0*0.1 = 1.0, unreliable
4.7 when the program is related to the environment or status, it must take the initiative to handle unexpected events, such as whether the file can
Logical locking, whether the printer is online, and so on.
4.8 unit testing is also a part of programming. Programs that submit joint debugging tests must pass unit testing.
5. reusability requirements
5.1 duplicate algorithms or code used to complete relatively independent functions should be abstracted as public controls or classes.
5.2 OO ideas should be taken into account for public controls or classes to reduce external connections and to consider independence or encapsulation.
5.3 a template should be created for public controls or classes.
Appendix: C ++ programming specifications, delphi for Reference
1. Applicability
This standard applies to developers who develop software programs using objective l c ++ and Borland C ++ ..
. 2 variable naming
The name must have some practical significance. The form is xAbcFgh, x is determined by the variable type, and Abc and Fgh indicate continuity.
Meaning string. If only two consecutive meaning strings can be capitalized, such as OK.
Specific routine:
BOOL type bEnable;
Ch * char chText
C * Class Object cMain (object instance)
H * Handle (Handle) hWnd
I * int
N * unsigned integer
P * pointer
Sz, str * string
W WORD
X and y coordinates
If the Char or TCHAR type is directly related to the Windows API, use the szAppName [10] format. Otherwise, use
FileName [10] format, a single character can also be expressed in lowercase letters;
Int type nCmdShow;
Long type lParam;
UINT type uNotify;
DWORD type dwStart;
PSTR type pszTip;
LPSTR type lpCmdLine
LPTSTR type lpszClassName;
LPVOID type lpReserved
WPARAM type wParam,
LPARAM type lParam
HWND type hDlg;
HDC;
HINSTANCE type
HANDLE type hInstance,
HICON type hIcon;
Int iTmp
Float fTmp
DWORD dw *
String, AnsiString str *
M _ class member variables m_nVal, m_bFlag
G _ global variable g_nMsg, g_bFlag
The following common variables can be used in local variables: nTemp, nResult, I, J (usually used for cyclic variables ).
Other resource handles are the same as above
. 3 constant naming and macro definition
Constants and macros must have some practical significance;
Constants and macros are defined between # include and function definitions;
Constants and macro definitions must all be written with uppercase letters, and can be connected with underscores (_) based on the continuity of meaning.
A simple comment must be provided on the right of the definition to describe its function;
Resource Name Definition Format:
Menu: IDM_XX or CM_XX
Bitmap: IDB_XX
Dialog Box: IDD_XX
String: IDS_XX
DLGINIT: DIALOG_XX
ICON: IDR_XX
. 4 function naming
The function prototype description includes reference of external and internal functions. The function source must be indicated on the Right of External Reference: Module
Block name and file name. If it is an internal function, you only need to comment out its definition file name;
The first letter must contain uppercase letters. A combination of uppercase and lowercase letters must be used to name a function. If necessary, an underline is used.
Interval, for example:
Void UpdateDB_Tfgd (TRACK_NAME); file: // Module Name: r01/sdw. c
Void PrintTrackData (TRACK_NAME); file: // Module Name: r04/tern. c
Void ImportantPoint (void); file: // Module Name: r01/sdw. c
Void ShowChar (int, int, chtype); file: // Local Module
Void ScrollUp_V (int, int); file: // Local Module
. 5 struct name
All struct types must be named in uppercase letters. In principle, the preceding dashes start. struct variables must be named in uppercase letters.
A combination of uppercase and lowercase letters. The first letter must contain uppercase letters. If necessary, an underline interval is available. For private data
Data Area, which must indicate the process to which it belongs. You only need to pay attention to the usage of global data definition.
Example:
Typedef struct
{
Char szProductName [20];
Char szAuthor [20];
Char szReleaseDate [16];
Char szVersion [10];
Unsigned long MaxTables;
Unsigned long UsedTables;
} DBS_DATABASE;
DBS_DATABASE GdataBase;
6. Control name:
Use a lower-case prefix to indicate a category
Use a lower-case prefix to indicate a category:
Fm window
Cmd button
Cob combo, drop-down list box
Txt text input box
Lab labal, label
Img image, image
Pic picture
Grd Grid, Grid
Scr scroll bar
Lst list box
Frm fram
7. Notes
In principle, the annotations must be in Chinese;
The file start comments include: company name, copyright, author name, time, module purpose, background, etc.
A process description must be added to a complex algorithm;
Function annotations include: input, output, function description, process processing, global variables, call samples, and other complex functions.
Variable usage instructions must be added;
Comments in the program include: modification time and author, easy to understand comments, etc;

Reference 1: annotation template at the beginning of a file
/*************************************** ***************************
** File Name:
** Copyright (c) 1998-1999 ********** Technology Development Department of the company
** Creator:
** Date:
** Modifier:
** Date:
** Description:
**
** Version:
**--------------------------------------------------------------------------
---

**************************************** **************************/
Reference 2: annotation template at the beginning of a function
/*************************************** **************************
** Function Name:
** Input: a, B, c
** ---
** B ---
** C ---
** Output: x ---
** X is 1, indicating...
** X is 0, indicating...
** Function description:
** Global variables:
** Call module:
** OPERATOR:
** Date:
** Modification:
** Date:
** Version
**************************************** ************************/
Reference 3: annotation template in the program
/*----------------------------------------------------------*/
/* Comment */
/*----------------------------------------------------------*/
8 programs
A. program coding strives to be concise and clear, avoiding too many branch structures and too skillful programs,
Do not use recursive mode.
B. When writing a program, you must also think about the test method. In other words, the unit test plan should be
Compile the program together.
C. The annotation must be consistent with the program.
D. The old statement must be closed with/**/after version archive. The old statement cannot be deleted or modified on its own, and
Record the changes to files and functions.
E. "{" and "}" at the beginning of each block in the program must be aligned. each nested block must be in one set,
Indent a tab with four spaces. The block type includes keywords such as if, for, while, and do.
F. For a relatively large function, each block and special function call must specify its function. For example:
:
Count. divisor = 1193280/freq; // compute the proper count
OutByte (unsigned short) 67, (unsigned char) 182); // tell 8253 that
Count is coming
OutByte (unsigned short) 66, count. c [0]); // send low-order byte
OutByte (unsigned short) 66, count. c [1]); // send high-order byte
××××××××××××××××××××××××××××××××××××××××××
Name the variable in bcb and delphi:
According to the Hungarian naming law
The name must be meaningful.
Form: Start with W in uppercase. For example, the copyright form of About is named WAbout.
File: start with an uppercase value of F, such as the About copyright form. The file is named FAbout. cpp.
Button: for example, the exit Button is named btnExit.
......
Base Class: adds a base tag, such as a report base class. The form is named WBaseRep and the file is named FBaseRep. cpp.
Resend
> 1. At the beginning of. h/. cpp, there should be a unified description of the format, including:
> A. File Name (FileName );
> B. Creater );
> C. File Creation Time (Date );
> D. Briefly describe the functions and purposes of the file (Comment ).
Good habits
> 2. Unless it is extremely simple, the function should be annotated. The content includes: function, entry/exit parameters, required
Yes
> You can also add remarks or additional instructions.
Good habits
> 3. The code length of each column is recommended to be 80 columns, and the maximum length cannot exceed 120 columns. The line alignment prevails.
It's too wide. My limit is 60 columns, because there are a total of 80 columns on the screen in text mode. If you use the BC class for editing
Window border and so on, so 80 columns are too wide
> 4. Loop and branch code. The judgment conditions and Execution Code cannot be on the same line.
Right
> 5. pointer definition. * can be followed by the type or before the variable name.
>
> Example: writable: int * pnsize;
>
> Can also be written as: int * pnsize;
>
> But cannot be written as: int * pnsize;
We recommend that you use the second method. Unless you add another rule: declare only one variable at a time, it will be confusing,
For example:
Int * a, B;
B seems to be a pointer, but it is not.
> 6. When calling a non-member function in a class member function, you must add ":" Before the non-member function name "::".
I don't think this is necessary. In my opinion, you should never let the name of your class member function and global function
Same (or similar)
> 7. If the function entry parameters have default values, comment them out.
>
> Example: BOOL CWpsDib: PaintDIB (CDC * pDC, CRect & rc,
> Int nBrightness, file: // * = 0 *//
> BOOL bGrayScale file: // * = FALSE *//)
Write a row for each variable and add/* in, out */comments if necessary.
> 8. else if must be written in one line.
Avoid structures like else if as much as possible
> 9. Rules related:
>
> 9.1 '{', '}' should have an exclusive row. This row can contain comments.
> 9.2 '{' must start with another line, and the code after '{' must be indented to a Tab. '{' And '}' must be in
Same
> A column.
> 9.3 If there is only one line of code after loops and branches, although '{' and '}' can be omitted, This is not recommended.
> Do. If this keyword is omitted, '{', '}' must be added '{','}'.
Hold your review because the GNU code specification is as follows:
If (NULL = ptr)
{
// Do something here
}
Or
If (NULL = ptr ){
// Do something here
}
It doesn't make sense to argue Which one is better. The key is unity. If you use VC, of course, your approach is the most convenient, but if you use
This is not the case for emacs or vi.

10. Space-related provisions.

10.1 there must be spaces on both sides of all the two-object and three-object operators. Spaces are not required at both ends of the single-object operator.
But in '-> ','::','. ',' [','] 'and other operators, and' & '(take address),' * '(value) and other operators must not have spaces.

10.2 for, while, if, and other keywords should be followed by a space, followed by '(', followed by no space;
There must be no space before.
I think adding spaces at both ends of parentheses is not a mistake, especially in an if statement with very complex conditions.
No space is allowed at both ends of the brackets.

10.3 when a function or macro is called, no spaces are allowed before or after.
10.4 when the type is forcibly converted, '('')' must have no spaces before and after
Same as above
11. indentation-related provisions
>
> 11.1 indent is in the unit of Tab. One Tab contains four spaces.
I think this value should be larger. I use eight spaces myself. If your code is too indented
If there is a problem with your program design.
> 11.2 In the following cases, the Code indent a Tab:
> 1. Relative function names and '{', '}' of the function body '{','}'.
> 2. Code after if, else, for, while, and do.
> 3. The code after the lines cannot be written within a row. The lines should be broken at a reasonable position. If +-*/is available
Operation
> Operator, the operator should be at the end of the previous line, rather than the first line of the next line.
This is my objection. The operator should be placed at the beginning of the next line so that you can clearly know that this line is a continuation of the previous line.
For example
If (something
& Somethingelse
& Otherthings)
If you write
If (something &&
Somethingelse &&
Otherthings)
But cannot see clearly
> 11.3 In the following cases, do not indent: case and default after switch


Author sdtarena

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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