C, C + + fundamentals and Programming style

Source: Internet
Author: User
Tags case statement

Original link

The cold Little Yang
Date: August 2013.
Source: http://blog.csdn.net/han_xiaoyang/article/details/10515417.
Disclaimer: Copyright, reproduced Please indicate the source, thank you.

Iv. expressions and Basic statements 4.1 operators and composite expressions

One of the first very important points is the priority of the C + + operator, and for a summary table, the combination of the special operator has been marked in bold boldface.

To be honest, it is very difficult to memorize the operator precedence and binding laws in the table above. Although there is a table, but also can not check the table every time, so we write the program as far as possible to follow the following rules:

If there are more operators in the line of code, use parentheses to determine the order in which the expressions are manipulated, and avoid using the default precedence .

Example: Word = (high << 8) |  Low and if ((a | b) && (A & c))

Some suggestions for composite expressions:

1) do not write compound expressions that are too complex. For example i = a >= b && c < d && C + F <= g + H; it's too complicated.

2) do not have multi-purpose composite expressions. For example d = (A = B + c) + R; should be split into two statements

3) Do not confuse the compound expression in the program with the "true mathematical expression".

4.2 If statement

The IF statement appears to be the simplest and most commonly used statement in the C ++/c language, but many programmers write an if statement in a way that implies an error. At the same time, some companies are very keen to examine this point in the written interview as a criterion for evaluating the basic knowledge of applicants.

Most of the observations are the statements of the IF statement in comparison to the 0 values:

1) Comparison of Boolean variables and 0 values

Do not compare Boolean variables directly with true, FALSE, or 1, 0. Assuming that the Boolean variable is named flag, the standard if statement that compares it to the 0 value is as follows:

if (flag) //indicates that flag is true

Other uses are bad styles , such as:

if (flag = = TRUE)

if (flag = = 1)

if (flag = = FALSE)

if (flag = = 0)

2) Comparison of integer variables and 0 values

You should use the integer variable with "= =" or "! = "Compare directly with 0. Assuming that the integer variable is named value, the standard if statement that compares it to the 0 value is as follows:

if (value = = 0)

if (value! = 0)

Cannot imitate the style of a Boolean variable and write it

if (value)//can make people misunderstand that value is a Boolean variable

if (!value)

3) Comparison of floating-point variables with 0 values (emphasis)

You cannot use a floating-point variable with "= =" or "! = "Compared to any number. Be aware that both F-loat and double-type variables have a precision limit. So be sure to avoid using the floating-point variable "= =" or "! = "In comparison with numbers, you should try to convert them into" >= "or" <= "forms.

Assuming that the name of the floating-point variable is x, you should

if (x = = 0.0)//Comparison of implied errors

Translates to

if ((X>=-epsinon) && (X<=epsinon))

Where Epsinon is the allowable error (i.e. precision)

4) Comparison of pointer variables with 0 values

you should use the pointer variable "= =" or "! = "Compared to null . The 0 value of the pointer variable is "EMPTY" (marked as null). Although the value of NULL is the same as 0, the meaning of the two is different . Assuming that the pointer variable is named p, the standard if statement that compares to the 0 value is as follows:

if (p = = null) //p is explicitly compared with NULL, emphasizing that p is a pointer variable

if (P! = NULL)

Do not write

if (p = = 0)// easy to misunderstand p is an integer variable

if (P! = 0)

Or

if (p)// easy to misunderstand p is a Boolean variable

if (!p)

The addition of the IF statement:if (null = = p) The odd format, not the programmer is wrong, is to prevent if (p = = null) is mistakenly written if (P = null), and intentionally put p and null upside down . The compiler considers if (P = NULL) to be legal, but indicates that if (N ULL = p) is wrong, because NULL cannot be assigned.

4.3 About circular statements

In a C++/C loop statement, the FOR statement uses the most frequently, while statement second, do statements are seldom used. Here are some points to note from the For loop:

1) in multiple loops, if possible, the longest loop should be placed in the topmost layer, the shortest loop is placed at the outermost level, to reduce the number of times the CPU crosses the loop layer.

For example, the right-to- left execution efficiency is high :

2) If there is a logical judgment in the loop and the number of cycles is large, it is advisable to move the logical judgment out of the loop body. such as the program in the right box, the simplicity of a slight decline, but the efficiency of the implementation is greatly improved

3) Do not modify the loop variable in the for loop to prevent the for loop from losing control.

4) It is recommended that the value of the loop control variable for the For statement be used as the "half open half closed interval" notation. As shown in the left :

4.4 About Switch statements

The switch statement format is as follows:

Note the point:

1) Do not forget to add break at the end of each case statement, or it will cause multiple branches to overlap (unless multiple branches are intentionally overlapping).

2) Don't forget the last default branch.  Even if the program really does not need default processing, it should keep the statement default:break; This is not superfluous, but to prevent others from mistakenly thinking that you have forgotten the default processing.

Five, constant

The C language is #define来定义常量 (called a macro constant). In addition to #define外还可以用const来定义常量 (called a const constant), the C + + language is an identifier whose value is constant during operation.

5.1. The meaning of constants

This in the written interview time also tested a few Ah, is the comparative basis of the more detailed things. Summed up the main is not to use constant words have the following three disadvantages:

1) The readability (comprehensible) of the program becomes worse. The programmer himself forgets what the numbers or strings mean, and the user is less aware of where they are coming from and what they are saying.

2) Enter the same number or string in many places of the program without writing errors.

3) If you want to modify the number or string, it will be changed in many places, both cumbersome and error prone.

Note, however, that when defining constants, we try to use represented that are intuitive to represent numbers or strings that will appear more than once in a program.

For example:

Macro constants for #define MAX/* C language */

const int MAX = 100; Const constants for the C + + language

const float PI = 3.14159; Const constants for the C + + language

5.2 C + + constants Two different ways to define

The C + + language can define constants in the form of Const and # define two, but it is recommended to use the former because:

1)const constants have data types, and macro constants do not have data types . The compiler can perform type safety checks on the former. Instead of only character substitution, there is no type safety check, and the substitution of characters can produce unexpected errors (marginal effects).

2) Some integrated debugging tools can debug const constants, but cannot debug macro constants .

5.3 Related rules for constant definitions

Simply put, when defining constants, it's best to follow these rules:

1) The constants that need to be exposed are placed in the header file, and no external constants are required to be placed on the head of the definition file. For ease of management, the constants of different modules can be centrally stored in a common header file.

2) If a constant is closely related to other constants, the relationship should be included in the definition and no isolated values should be given.

For example: const float RADIUS = 100;

const FLOAT DIAMETER = RADIUS * 2;

5.4 About constants in classes

It is very important and often a mistake, and sometimes we want certain constants to be valid only in the class, so it is assumed that the data members should be modified with Const. However, const data members are constants only for the lifetime of an object and are mutable for the entire class, because a class can create multiple objects, and the values of the const data members of different objects can be different.

Therefore, you cannot initialize a const data member in a class declaration . Because the object of the class is not created, the compiler does not know what the value of size is. the initialization of a const data member can only be done in the initialization table of the class constructor .

If you want to build constants that are constant throughout the class . Const data members are not complete and should be implemented with enumeration constants in the class.

Class A

{...

enum {SIZE1 = +, SIZE2 = 200}; Enumeration constants

int ARRAY1[SIZE1];

int array2[size2];

};

Enumeration constants do not consume objects ' storage space, they are evaluated at compile time. The disadvantage of an enumeration constant is that its implied data type is an integer, its maximum value is limited, and it cannot represent a floating-point number (such as pi=3.14159).

C, C + + fundamentals and Programming style (RPM)

Related Article

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.