High quality C++/C Programming Guide

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

First of all, strongly recommend Dr. Lin Rui this "high quality C++/C programming guide", please spend one or two hours reading this book 100, you will be benefited. Hastily read, individual harvest records are as follows.

header file for a brief explanation:

(1)The header file to call library function. In many cases, the source code (or not) to the user inconvenience released, as long as the header files and binary database to the user. Users only need to follow the interface declaration in the header file to call library function, but does not need to care about how to realize the interface. The compiler will extract the corresponding code from the library.

(2)The header file can strengthen type safety inspection. If an interface is implemented or used, the way and the header file statement is inconsistent, the compiler will point out a mistake, this simple rules can greatly reduce the burden of the programmer debugging, error correction.

Another: the extern can be placed in the variable or function, in order to define mark the variable or function in other documents, suggesting that the compiler encounters the variables and functions in other modules for its definition. If the function declaration with the keyword extern, is only a hint of this function may be defined in another source file, no other effect.

"

A. after each class declaration, after each function defined over to add the line.

B. in the body of a function, not a blank line between Luo Yi is closely related to the statement, other places should be blank lines to separate. (this is a worthy of note)

lines of code

A. is a line of code to do only one thing only, such as the definition of a variable, or just write a statement. Such code is easy to read, and convenient to write notes.

b.if,for,while,Do statement since for a row, execute the statement shall be followed. No matter how many to execute statements with {}. This can prevent the writing errors.

for(initalization;contition;update)

{
    dosomething();
}
//Blank line
other();

C. as far as possible, the variables are initialized in the definition of variables at the same time (the nearest principle)

code in space

To save space, such as const, virtual, inline after the keyword A., case and if, for, while; the name of the function after not space, followed by the left parenthesis' (', with the key difference.

b.After the commas and semicolons to leave spaces ; "=", "+ =" > ";" <= = ",", "+", "*", "%", "& &", "||", "<<," before and after "^" two binary operators should add space < /font>; unary operator without spaces.

C. like "()", ".", "->" and this kind of operator without spaces.

Expression of D. for long for statements and the if statement, in order to compact side can be properly removed some spaces.

for (i=0; i<10; i++) // Good style

long separation

Code for maximum length should be controlled within 70 to 80 characters. Long expression to into a new row in the lower precedence is split, operator on the new song (so as to highlight the operator). A new resolution should be proper indentation, make neat layout, the statement read.

if ((very_longer_variable1 >= very_longer_variable12)
    && (very_longer_variable3 <= very_longer_variable14)
    && (very_longer_variable5 <= very_longer_variable16))
{
    dosomething();
}

comments in italics

The A. annotation is to code "prompt", rather than the document. In the notes program can not proceed, comment too much will let people see things in a blur. Less annotation pattern.

B. writes the code edge annotations, modify the code to modify the corresponding notes at the same time, to ensure the consistency of the comments and code. no longer useful comments to delete.

C. try to avoid the use of abbreviations in the notes, especially the common abbreviations.

The D. annotation position should be with the described above or adjacent to the code, can be placed in the code, can not be placed under the.

F. when the code is relatively long, especially when multiple nested in some paragraphs, shall end with notes, easy to read.

format

The class format has two main ways:

(1)The private data type is written on the front, while the public type of function is written on the back. The design of "this layout programmers that kind of data centered", focused on the internal structure of class.

(2)The public type of function is written on the front, while the private data type is written on the back. The design of "this layout programmers that class to act as the center", the focus is the class should be what kind of interface (or service).

The reader is advised to use "to act as the center" way of writing, which is considered first class should provide what functions.

class A
{
    public:
        void Func1(void);
        void Func2(void);
        …
    private:
        int i, j;
        float x, y;
        …
}

common rules

The A. identifier should be intuitive and can spell, is expected to be the knowledge meaning; the length of identifier shall comply with the "min-length & & max-information" principle.

B. naming rules as much as possible with the operating system or development tools used by the style consistent.

For example, the identifier for the Windows application usually uses the "sensitive" mixed mode, such as AddChild. The identifier for the Unix application usually uses "lowercase underlined" approach, such as add_child. Don't take this two kind of style mixed use.

The C. variable name should use the "noun" or "Adjective + noun"; global function name should use "verb" or "Verb + noun" (verb object phrases).

D. try to avoid the number, names appear in such as Value1, Value2, unless the logic does need number. This is to prevent the programmer laziness, refused to name the brains and cause no meaningful name (because the number the most convenient).

simple Windows application naming rules

The A. class name and function names begin with a capital letter word combination

The B. variables and parameters with a lower case letter word combination.

C. constant use all capital letters with underline words, segmentation.

D. static variables (prefixed with s_ static).

E. if it is necessary for global variables, the global variable g_ (Global prefix).

F. data members of a class prefix m_ (member), which can avoid the parameter data members and member function with the same name.

G. in order to prevent conflicts in some identifier a software library and other software libraries, can be prefixed with various identifier can reflect the nature of software.

if statement in italics

Don't be a floating-point variable using "= =" or"! Compared with any digital = ".

if ((x >= -EPSINON) && (x <= EPSINON))
//Where EPSINON is the permissible error (i.e., accuracy). 

Sometimes we may see if (NULL = = P) this odd format. The program is not wrong, the programmer in order to prevent the if (P = = NULL) mistakenly written in if (P = NULL), and interested in the P and NULL reverse. The compiler considers if (P = NULL) is legal, but pointed out that the if (NULL = P) is wrong, because the NULL cannot be assigned.

Combined programs sometimes encountered if/else/return, should be the following bad style program

if (condition)
    return x;
return y;

Rewrite

if (condition)
{
    return x;
}
else
{
    return y;
}

Or rewritten into a more concise

return (condition ? x : y);

cycle statement efficiency

C++/C statement, for statement to use the highest frequency, followed by while statements, do statements rarely use. The basic way to improve the cycle efficiency is to reduce the complexity of the loop body.

In the multiple loop, if possible, should be the longest cycle in the innermost layer, the shortest cycle on the outer layer of , in order to reduce the CPU cross cut the number of circulating layer.

switch statement in italics

Don't forget that last default branch. Even if the program does not really need the default processing, also should keep the default statement: break; do not make an unnecessary move, but in order to prevent others think you forget default.

goto statement in italics

We advocate using less, goto statements, and not disabled.

const and #define

C++ const can be used to define constants, #define can also be used to define constants. But the former has more advantages than the latter:

(1)The data type of const constant, and macro constant no data type. The compiler can on the type safety inspection . And the latter only character replacement, no type checking, and replace may produce unexpected errors in character (marginal effect).

(2)Some integrated debugger can debug const constants, but not to debug macro constant.

Suggestion: in C++ programs only use the const constant and do not use the macro constant.

class

Sometimes we want some constant is only valid in a class. Because the #define macro defined constants are global, can not achieve the purpose, then most probably it did not actually happen to think that should be modified by const to realize data members. Const data members does exist, but its meaning is not what we expect. Const data members only in a certain object survival period is constant, but for the whole class is variable, because the class can create multiple objects, different objects in the const data member values can be different. Cannot initialize the class declaration in a const data member. The usage is wrong, because the class object was not created, the compiler does not know what is the value of SIZE.

class A
{
    …
    const int SIZE = 100; // Error attempting to initialize the data members, const in a class declaration
    int array[SIZE]; // Unknown error, SIZE
};

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

class A
{
    …
    A(int size); // Constructor
    const int SIZE ;
};
A::A(int size) : SIZE(size) // A constructor initializer list
{
    …
}
A a(100); // Object a SIZE 100
A b(200); // Object B SIZE 200

How can we build are constant throughout the class of constant? Don't count on const data members, should use the classes in the enumeration constants to achieve. For example

class A
{
    …
    enum { SIZE1 = 100, SIZE2 = 200}; // Enumeration constants
    int array1[SIZE1];
    int array2[SIZE2];
};

Enumeration constant not occupy storage space objects, they are all evaluated at compile time. Enumeration constant drawback: implicit data type it is an integer, the maximum value is limited, and can not be said float (such as PI=3.14159).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Gino at November 12, 2013 - 10:52 PM