How to quickly and effectively find out program errors (in C)
I think most people who have just started to learn the C language are the same as I used to. The program code that I typed out was wrong during debugging and running, but I don't know where the error is, how to modify. The first reaction of most people is to get confused, and then simply modify the code according to their own logic. Instead, the result becomes more and more wrong. The following are some of my summary methods for finding errors.
First, check whether the code has a logic error:
1. Unused values before using the variable
Instance:
Int main ()
{
Int x = 5, y, z;
Z = x * y;
Printf ("% d", z );
Return 0;
}
In this program, the variable y is not assigned a value before use. Therefore, the result output value of z is that the system randomly assigns a value to y and multiplied by x.
2. confuse the value assignment symbol "=" with the equal symbol "="
Instance:
The following statements are available:
If (a = 5)
{
Printf ("a equals 5 ");
}
In this way, the output result will always be "a = 5" because no matter what a is before when the if (a = 5) is executed, at this time, the value of a is assigned to 5 again, instead of comparing the value of a with 5, and the correct expression is:
If (a = 5)
{
Printf ("a equals 5 ");
}
3. The break is missing in the switch statement, and ";" is missing after while () in the do {} while () statement.
First, check whether the Code has an algorithm error:
Take the algorithm for exchanging two variables as an example:
The correct algorithm is as follows:
Int main ()
{
Int a = 5, B = 10, temp;
Temp =;
A = B;
B = temp;
Printf ("% d", a, B );
Return 0;
}
If the order of temp = a; a = B; B = temp; is changed randomly, the values of a and B are not exchanged.
Finally, it is also the most common mistake:
For example, if you forget to input ";" after a statement is completed, you forget the address character "&" before assigning a value to parameter a in the input statement "scanf (" % d ",.
I want to follow the above steps to find out the code errors will become effective quickly, please try it!