Debugging and Testing
Syntax Errors
Syntax refers to the grammar, structure and order of the elements in a statement. A syntax error occurs when we break the rules, such as forgetting to end a statement with a semicolon. When you compile the program, the compiler will produce a list of any syntax errors that it may encounter.
A good compiler will output the list with a description of the error, and may provide a possible solution. Fixing the errors may result in further errors being displayed when recompiled. The reason for this is that the previous errors changed the structure of the program meaning further errors were suppressed during the original compilation.
Similarly, a single mistake may result in several errors. Try putting a semicolon at the end of the main function of a program that compiles and runs correctly. When you recompile it, you will get a huge list of errors, and yet it's only a misplaced semicolon.
As well as syntax errors, compilers may also issue warnings. A warning is not an error, but may cause problems during the execution of your program. For example assigning a double-precision floating point number to a single-precision floating point number may result in a loss of precision. It is not a syntax error, but could lead to problems. In this particular example, you could show intent by casting the variable to the appropriate data type.
Consider the following example where x is a single-precision floating point number, and y is a double-precision floating point number. y is explicitly cast to a float during the assignment, which would eliminate any compiler warnings.
x = (float)y;
Logic Errors
Logic errors occur when there is an error in the logic. For example, you could test that a number is less than 4 and greater than 8. That could not possibly ever be true, but if it is syntactically correct the program will compile successfully. Consider the following example:
if (x < 4 && x > 8)
puts("Will never happen!");
The syntax is correct, so the program will compile, but the puts statement will never be printed as the value of x could not possibly be less than four and greater than eight at the same time.
Most logic errors are discovered through the initial testing of the program. When it doesn't behave as you expected, you inspect the logical statements more closely and correct them. This is only true for obvious logical errors. The larger the program, the more paths there will be through it, the more difficult it becomes to verify that the program behaves as expected.
|