Good subtotal programming habits (1). Subtotal programming habits

Source: Internet
Author: User

Good subtotal programming habits (1). Subtotal programming habits

This article records the good programming habits you have experienced in the recent learning and coding processes. If you find anything inappropriate, leave a message to indicate it.

  • Initialization of variables (common variables and pointers.

    Explanation: For C/C ++, the declared variables are not initialized, so the values in them are some (previously the value of the memory). Therefore, for the auto-increment and auto-increment operations, errors may occur here. Pointers are even more dangerous. If the declared pointer is not assigned a value, it also contains a value. At this time, you do not know where the declared Pointer Points. When you use it, it will assign a value to the pointer, during this period, if you use a pointer and modify the content, it is an ignorant modification, which is the most terrible. The Code is as follows:

    # Include <QCoreApplication> # include <QDebug> int main (int argc, char * argv []) {QCoreApplication a (argc, argv); int I; qDebug () <++ I; // 4203055 int * p; qDebug () <p; // 0x22ff88 p = (int *) malloc (sizeof (int) * 1 ); qDebug () <p; // 0x847b38 // below are good habits int j = 0; qDebug () <++ j; // 1 int * pointer = NULL;
        qDebug()<<pointer;//0x0    pointer = (int *)malloc(sizeof(int)*1);    qDebug()<<pointer;//0x847b48    qDebug()<<"Hello word!";        return a.exec();}
  • Release and empty pointer

    The memory dynamically allocated for pointers in the program, at the end of the program, not only develops the habit of releasing memory, but also raises the habit of null pointers. That is to say, you have released the pointer's memory at the end, but the pointer still points here, so there is a security risk, so leave it empty. The Code is as follows:

    # Include <stdlib. h ># include <iostream> using namespace std; int main () {int * pointer = NULL; // the pointer must be NULL pointer = (int *) malloc (sizeof (int) * 1); cout <"Hello World! I am over! "<Endl; // The following shows a good pointer end method (also empty) free (pointer); pointer = NULL; return 0 ;}
  • The dynamic memory applied by malloc has many pitfalls. Do not use strlen for measurement.

    Explanation: this error once caused a sensation in the whole QQ Group. In fact, when you look at the content in the memory that you opened dynamically, you will suddenly realize it. First, let's briefly explain that the strlen function in C language is not clear. All the memory we use, if not initialized, will certainly have content (Computer principles), including the memory we dynamically open up, and the role of the strlen function, measure the length of a string (ended with '\ 0 ). unknown possibilities exist in the unknown world. Unknown memory may include '\ 0' in the middle. The use of strlen measurement will produce unexpected results. The Code is as follows:

    # Include <string. h> # include <stdlib. h> # include <iostream> using namespace std; int main () {char * pointer = NULL; // the pointer must be NULL pointer = (char *) malloc (sizeof (char) * 15); cout <"string:" <strlen (pointer); // output 3 cout <"value: "<pointer; cout <endl; char * pointer1 =" You Love Me. "; // 12 cout <" string1: "<strlen (pointer1); cout <endl; return 0 ;}
    Explanation: in C/C ++, a statement is called an "open circuit ". For example:If (condition 1 & condition 2)To be true, both conditions must be true. In practice, if condition 1 is false, the program will not determine whether condition 2 is true or false. This is an open circuit phenomenon. Likewise,If (condition 1 & condition 2)If condition 1 is true, the second condition is not determined. What kind of error will happen to our instance? First, let's saywhile(NULL != p && item->data > p->data )Yes, but if you exchange the two conditions before and after, a bug is created. My idea is to first determine whether the point of p exists. If yes, thenp->dataTrue or not. If the first and second conditions are exchangedp=NULLThen,p->dataWhere will it be? Where are you going to read data? The program will be killed by you.

  • Compare variables in a condition sentence
    # Include <iostream> using namespace std; // each of the following variables is compared with the zero value. Select the optimal method int main () {bool flag; if (flag = true) {} if (flag = false) {}// variables of the bool type should select the following standard if (flag) {}// this method is optimal, because the true value is not sure if (! Flag) {} int value; if (value = 0) {} // This method is good. The following will be a misunderstanding: boolean type if (value! = 0) {} if (value) {} if (! Value) {} float x; if (x = 0) {} if (x! = 0) {} // The following method is good, because all float and double types have precision, so convert to the following form to compare if (x> =-EPSINON) & (x <= EPSINON) {} if (X <-EPSINON) | (x> EPSINON) {} int * p; if (p = NULL) {} // such a good if (p! = NULL) {} if (p = 0) {} if (p! = 0) {} // sometimes it will write like this (think about the benefits of this method) if (0 = value) {} if (NULL = p) {} cout <"Hello World! "<Endl; return 0 ;}
  • Do not use statements containing Side Effects in judgment Conditions

    Explanation: first, what is a side effect is a statement that changes the state of the program. Check the code instance:

    If ('y' = getchar () | 'y' = getchar () // getchar () from the buffer, read one fewer, if the program status changes during the read process, errors may occur. {}// The standard is as follows: char ch = toupper (getchar (); // you can understand if ('y' = ch ){}
  • When defining a function or variable name, be careful when conflicting with keywords or standard functions.
  • The form parameter in the function. If it is not changed in the function body, it is set to a const constant.
  • For parameters passed in the function, perform a security check.
  • The definition of a variable should be "when to use, when to define, where to use, and when to define", the location of the definition of the variable should be a little more compact with the place where it is used.
  • Good Programming Habits can be fully realized only when you write a program. At the same time, if you have a better understanding, you can leave a message below to learn and make progress together.

    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.