C ++ beginners cultivate a good programming style

Source: Internet
Author: User

Martial arts experts with deep internal skills are often unremarkable. Similarly, programmers will not use strange tricks to write programs. A good programming style is a prerequisite for high-quality programs. The following uses C ++ as an example to describe it.
I. Naming Conventions
Many people use Pinyin to name functions or variables when programming. This does not mean that you are very patriotic, but will confuse people who use this program (many Southerners do not understand pinyin, ). The English in the program is generally not too complex, and the words should be accurate. The Hungarian naming convention [Maguire 1993] was proposed by Microsoft. Although it was cumbersome, it became natural to get used to it. No one forces you to adopt the naming method, but one thing should be done: Your program name must be consistent.
The naming conventions used in programming are as follows:
(1) macro definitions are expressed with uppercase letters and underscores, for example, MAX_LENGTH;
(2) The function is composed of words starting with an upper-case letter, such as SetName and GetName;
(3) the pointer variable is prefixed with p, for example, * pNode;
(4) Add the BOOL variable with the prefix B, such as bFlag;
(5) The int variable is prefixed with I, such as iWidth;
(6) Add the prefix f to the float variable, such as fWidth;
(7) The double variable is prefixed with d, for example, dWidth;
(8) string variables are prefixed with str, such as strName;
(9) Add the prefix e to the enumerated variables, such as eDrawMode;
(10) Add the prefix m _ to the member variables of the class, such as m_strName and m_iWidth;
For int, float, and double variables, if the meaning of the variable name is very obvious, the prefix is not added to avoid being cumbersome. Such as the three-dimensional coordinates (x, y, z) of the int type I, j, k, and float variables used for loops.
Ii. Use assertions
Programs are generally divided into Debug and Release versions. The Debug version is used for internal debugging, And the Release version is released to users. Assert is a macro that only works in the Debug version. It is used to check the situation where "no" occurs. The following is a memory replication program. During the running process, if the assert parameter is false, the program will be suspended (A dialog is usually prompted, description of where the assert is triggered ).


 
Assert is not a hasty macro. To avoid the differences between the Debug and Release versions of the program, assert should not produce any side effects. So assert is not a function, but a macro. Programmers can regard assert as a harmless testing method that can be safely used in any system status.
There are few more frustrating things than the assertions that trace the program, but do not know the role of the assertions. You have made a lot of time, not to exclude errors, but to find out what the error is. Sometimes, programmers occasionally design wrong assertions. Therefore, if you do not know what the assertions check, it is difficult to determine whether the errors appear in the program or in the assertions. Fortunately, this problem is well solved by adding clear notes. This is obvious, but few programmers do this. This is like a person in the forest, seeing a "dangerous" big sign on the tree. But what is the danger? Will the tree fall? Is there a waste well? Is there a beast? Unless you tell people what danger is, this warning board cannot play a positive and effective role. Incomprehensible assertions are often ignored or even deleted by programmers. [Maguire 1993]
The following principles Use assertions:
(1) Capture exceptions that should not occur with assertions. Do not confuse the differences between illegal and wrong situations. The latter must exist and be handled.
(2) Use assertions to confirm the function parameters.
(3) When writing a function, you should repeat it and ask yourself: "What assumptions do I plan to make ?" Once the assumptions are determined, we need to use assertions to check the assumptions.
(4) In general textbooks, programmers are encouraged to design error-proof programs, but remember that such programming style will conceal errors. When programming against errors, if "impossible to happen" does happen, Use assertions to trigger an alarm.
3. new, delete, and pointer
In C ++, the operator new is used to request memory, and the operator delete is used to release memory. In C language, the function malloc is used to request memory, and the function free is used to release memory. Since C ++ is compatible with C language, new, delete, malloc, and free may all be used together. New can do more work than malloc. It can apply for the object's memory, but malloc cannot. The pointer in C ++ and C languages is extremely powerful, and errors may cause disasters. For a pointer p, if the new memory is used, delete must be used instead of free. If the memory is applied for using malloc, it must be free instead of deleted. After you use delete or free to release the memory referred to by p, you should explicitly set p to NULL immediately to avoid an error when you use p next time. The example program is as follows:


 
We also need to prevent "wild pointer", which is a pointer to the "junk" memory. There are two main causes:
(1) the pointer is not initialized.
(2) The Pointer Points to the released memory, which is the most difficult to prevent. The example program is as follows:


 
4. Use const
When defining a constant, const is more flexible than # define. A constant defined by const contains a data type, which can be used in logical operations. For example:


In addition to defining constants, const also has two "protection" functions:
I. The parameter values of the mandatory protection function are not changed.
In the following program, function f does not change the value of the input parameter name, but function g and h may change the value of name.


 
For a function, if the '&' or '*' type parameter is used only for input but not for output, you should add const before the parameter, to ensure that the function code does not change the value of this parameter (if the value of this parameter is changed, the compiler will receive an error warning ). Therefore, the functions g and h in the above program should be defined:
 
2. The member function of the force protection class does not change the value of any data member.
In the following program, the member function Count of the class stack is only used for counting. To ensure that Count does not change the value of any data member in the class, the function Count should be defined as the const type.
 
5. Other suggestions
(1) do not write an overly complex statement. Compact C ++/C code does not see machine code that can be efficient, but it will reduce the comprehensibility of the program, the probability of program errors increases.

(2) do not compile functions that combine multiple functions. Do not mix normal values and error marks in the return values of functions.
(3) do not program BOOL values TRUE and FALSE with values 1 and 0. In most programming languages, FALSE is defined as 0, and any non-0 value is TRUE. Visual C ++ defines TRUE as 1, while Visual Basic defines TRUE as-1. The example program is as follows:
 
(4) Be careful not to write "=" as "=". The compiler will not automatically detect such errors.
(5) do not write 123 as 0123. The latter is a numerical value of octal.
(6) record the programming errors that you often make and paste them into tables next to your computer.
Summary
C ++/C programming is as profound and profound as the martial arts of Shaolin Temple. After eight years of practice, I learned only two or three of them. So no matter what time, do not feel that your programming level is the highest in the world. To see other people's good technologies and styles, you must learn with an open mind. This chapter has little content, just like giving you only one bayberry to eat when you are thirsty. You must not be addicted to it. I recommend a good book called C ++ FAQs [Cline 1995] by Marshall P. Cline. You will be full of praise after reading it. C ++/C programs can be compiled. Don't be so proud. This is just a basic skill requirement for programmers. If you compare System Analysis and system design to "strategic decision-making", programming is only "tactical" at best ".
If the commander is an idiot, the soldiers will be defeated again if they are brave. Therefore, programmers should not only focus on the program, but also learn more. We should learn from our children in Beijing and Hu Tongli. They will be able to give advice and comment on world events at a young age.

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.