Errors -- Syntactical vs. Logical
Before a program can be completed, the programmer must ensure that his/her program works, as required, through extensive testing and debugging. Errors found during this stage include:
· syntax (compile-time) errors
· logical errors
· linking errors
· run-time errors
Syntax (Compile-Time) Errors
The most common type of error is the syntax (or compile-time) error, in which a segment of code within a program has violated one of the grammar or syntax rules of the C++ compiler and are reported when the program is compiled. Syntax errors are relatively easy to fix.
The most difficult types of errors to find are errors contained within the logic of an algorithm. Logical errors are generally found during the execution of the program in the form of incorrect results. The only way one can be confident of having a logic-error free program is by testing it with a wide range of data, and then comparing the actual and expected results with each other.
The following code segment provides examples of both syntactical and logical errors in C++:
// This program demonstrates the difference between syntactical and
// logical errors.
// It accepts an integer and determines whether the integer is either
// "greater than", "less than", or "equal to" 0.
cout >> "Input a number: ";
cin >> i;
if (i > 0)
cout << "Integer is larger than 0\n";
else if (i <= 0)
cout << "Integer is smaller than 0\n";
cout << "Integer is equal to 0\n";
When compiled produces the following error:
sample.c: In function `int main()':
sample.c:8: invalid operands to binary >>
Examining line 8 (cout >> "Input a number: ";) reveals that the data directors are pointing the wrong way. The corrected statement should read:
cout << "Input a number: ";
With the above change saved, the compiler no longer complains of any errors and compilation is a success. However, when the program is tested with a wide range of data (something you should try to do with all your programs!), a value of 0 does not yield the proper response. We can do one of two things: use a debugger or "walk" the program by hand.