C language code specification

Source: Internet
Author: User
C language code specification
From csdn Forum
Original caiyi9000

 

I developed the underlying C language and accumulated some code writing experience for your reference:

1. C language writing Specification

1.1 symbol naming rules
1.1.1 The symbolic name includes the module name, constant name, label name, and subroutine name. These names should reflect the actual things they represent and have some significance, so that they can be known and understood, and help to understand program functions. The naming method is Hungarian. The rules are as follows:
(1) All macro definitions, enumeration constants, and const variables are named in uppercase. Separate each word with an underscore in a compound.
(2) In compound words, the first letter of each word is capitalized. In addition to rule 5.1.1.1, do not use underscores.
(3) The first letter of the class, type definition, and enumeration name is capitalized.
(4) The function name is composite. The first word is in lowercase, followed by the first letter and the other letters in lowercase. If it is a single word, use all lowercase letters.
(5) I, J, K, and so on can be used for cyclic variables, which are not restricted by the above rules.
(6) the class member variables should start with M.
(7) The global variable header is g _.
(8) The temporary variable header is TMP _.
(9) Naming the variables in the structure follows the naming principle of the specific meanings of the variables.
(10) use the prefix of lowercase letters to indicate the type of the variable, and the next letter with the prefix should be capitalized.
Table 1
Word header type
Ch char l long
I integer U unsigned
B Boolean P pointer
F float LP long pointer
D double S string
St structure sz ascii string
By byte n short int
H handle X and Y are the X and Y coordinates respectively.
Dw dword fn Function

Table 2
Word header change name
Task task sig Signal
SB binary semaphores WD Watchdog
SM Mutual Exclusion
Semaphores TM Timer
SC counting semaphores MSG message
Pipe
Example:
# Define array_size 24/* Rule 5.1.1.1 */

Int g_iflag;
Class myclass/* Rule 5.1.1.3 */
{
};

Void somefunc ()/* Rules 5.1.1.2 and 5.1.1.4 */
{
. 2.
Q/ECC/bj 010-2001

Int narray [array_size];
Unsigned char uchbyte;
Char szname [];
Char * pszname = szname;
}
(11) some headers (such as P and U) can be combined with other headers.

Example: wdog_id wdid;
Wdog_id g_wdid;/* global watchdog ID, so it starts with G */
1.1.2 The name length should not be too long or too short. Too long names can increase the workload and blur the program logic. Too short names cannot express the actual meaning of symbols. Agreed length range: 3-31;

1.2 data and Function Description
1.2.1 The data description sequence should be standardized to make data attributes easy to find and facilitate testing, troubleshooting, and maintenance. The order of description should be fixed and should be sorted by logical function. The following sequence is recommended in the logical function block: integer description, real description, character description, and logical amount description.
1.2.2 If a complex data structure is designed, the meaning and purpose of its variables should be described through annotations.
1.2.3 use exception declaration in function declaration.
For example, void F () Throw (toobig, toosmall, divzero );
When declaring a function, list the exceptions it throws, so that the function user can understand what exceptions may occur.

1.3 program Annotation
1.3.1 program annotation is one of the important means for communication between programmers and program readers in the future. Annotations include file annotation, function annotation, and function annotation.
1.3.2 notes for formal procedures:
-- The number of comment lines accounts for 1/3 to 1/2 of the entire source program.
1.3.3 the file comment is located at the beginning of the entire source program, and there are two lines to start the program body after the comment. It includes:
-- Program title.
-- Purpose and function description.
-- Description of the file author and the last modification date.
Example:
. /*************************************** *****************************
(Empty line)
Title: Demo. c
Function: test various system calls of VxWorks.
Note:
This program tests various VxWorks System Call functions. Including creation and suspension of tasks (taks), and synchronization between tasks through signal lights, and communication through message queues.
The program creates two tasks: a high-priority task and a low-priority task. The two tasks are synchronized through a binary signal lamp and communicated through the message queue.
Current version: x. x
Information modified: 200000006.05 John, initial version
20002.167.05 Tom, bug XXXX fixed
**************************************** **********************/
(Leave 2 blank lines to start the program body)

1.3.4 function comments are usually placed at the beginning of each function or process. It should provide an overall description of the function or process, which is helpful for understanding the program itself. It generally includes the following entries:
-- Module title.
-- Describes the functions and objectives of this module.
-- Call format
-- Interface Description: Includes input, output, return value, and exception.
-- Algorithm. If some complicated algorithms are used in the module.
Example:
File: // (the comment must start with a blank line from the previous function)
(The beginning of the comment is separated from the last line of the previous function)
/*************************************** *****************************
Title: assignmentcomplete
Function: BSC => MSC message generation function. Generating assignment_complete indicates the completion message (bsmap message ).
Format:
Int assignmentcomplete (INT icellid, int iservicechannnelnum, char * pszmsgdata)
Throw (exception1, exception2)
Input:
Int icellid: ID of the cell where Ms is located
Icellid value: 0x00 --- 0xff. 4.
Q/ECC/bj 010-2001

Int iservicechannnelnum: Business Channel Number occupied by Ms
Output:
Char * pszmsgdata: indicates the completion message data.
Returned value: 0x00 normal
Exception: exception1 exception 1, exception2 exception 2
**************************************** ****************************/
(Directly start the program body after the annotation, without blank lines .)
1.3.5 functional comments are embedded in the source program and used to describe what the subsequent statements or program segments do, that is, to explain what to do below or what will happen if the following statements are executed. Instead of explaining how to do the following, it is often the same as the program itself.
Example:
/* Add amount to total */
Total = Amount + total;
Such annotations only repeat the following program and have no effect on understanding its work. The following comments help readers understand them.
/* Add the monthly sales volume amount to the total annual sales volume */
Total = Amount + total;
1.4 function writing should be as short and concise as possible, generally no more than two screens for debugging and understanding.

1.5 statement Structure
To ensure a clear statement structure and program readability, pay attention to the following issues when writing software programs:
-- Write only one statement in one row, and use spaces, blank lines, and migration to ensure a clear visual effect.
-- Each nested function block uses a tab indent (which can be set to four spaces). Braces must be placed in the next row of the Condition Statement and one row separately to facilitate matching:
For example, a program is as follows:
For (I = 1; I <n-1; I ++) {T = 1; for (j = I + 1; j <n; j ++ ){
If (A [J] <A [T]) t = J; If (T! = I) {work = A [T]; A [T] = A [I]; A [I] = work ;}}}
Should be written
For (I = 1; I <n-1; I ++)
{
T = 1;
For (j = I + 1; j <n; j ++)
{
If (A [I] <A [J])
T = J;
If (T! = 1)
{. 5.

Q/ECC/bj 010-2001
Work = A [T];
A [T] = A [I];
A [I] = work;
}
}
}

-- There must be no empty rows in the file without rules, for example, 10 empty rows in a row.
Generally, there are two or three rows of null behavior between a function and a function;
Inside the function body, two logically independent function blocks can be empty rows, generally 1-2 rows.
-- Clarity should be considered first in programming; Do not deliberately pursue skills to make the program hard to understand.
-- The length of each line should not exceed the screen width, and should not exceed 80 characters.
-- Unless there are special requirements on efficiency, programming should be made clear first, and efficiency second.
-- Use the function library whenever possible.
-- Try to replace repeated functional code segments with common procedures or subprograms. Note that this code should have an independent function and should not be extracted to form a common process or subprogram just like the code form.
-- Use parentheses to clearly express the Operation Sequence of arithmetic expressions and logical expressions. For example, writing X = a * B/c * D as X = (a * B/c) * D can avoid reader misunderstanding as X = (A * B) /(c * D ).
-- Avoid unnecessary transfer.
-- Avoid complicated conditional tests.
-- Avoid excessive loop nesting and conditional nesting.
-- Do not use operators such as * =, ^ =,/=.
-- A function cannot exceed 200 rows. Avoid more than 2000 lines of a file.
-- Avoid using the go to statement whenever possible.
-- Avoid using multiple value assignment statements, such as X = y = z;
-- Do not encourage adoption? : Operator, such as Z = (A> B )? A: B;
-- Do not use an empty if else statement. For example
If (cmychar> = 'A ')
If (cmychar <= 'Z ')
Printf ("This is a letter/N ");
Else
Printf ("This is not a letter/N ");
Whether or not else denies which if is likely to cause misunderstanding. You can add {} to avoid misunderstanding.
-- Try to reduce the number of condition statements that use the "negative" condition. For example:
Set if (! (Cmychar <'0') | (cmychar> '9 ')))
Change to If (cmychar> = '0') & (cmychar <= '9 '))

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.