C++ Programmer Alerts
(Page 1 of 4 )
In this article I show you how you can avoid common programming errors in C++. There will be examples (including code) that you can use to practice on your own. Are you interested? Then click on the link and start reading.
FUNDAMENTALS
Briefly, here are some fundamental points that show good style:
Start the program with a short statement of what the program does.
List the author(s) of the programs.
Give the date the program was written.
Use comments and blank lines to delineate sections of the programs.
CONTROL CONSTRUCTS
Assignment and Equality Operators
A common programming error is the confusion between the == and = operators, especially by “newbies.”
Instead of writing,
j==5
for example, a programmer may write
j=5
The first expression is an equality expression and is true whenever j is 5. The second expression is an assignment expression where j is assigned to 5.
Rounding Errors
Be careful when using the equality operators ( == , != ) with floating point types. The finite precision of floating-point types allows round-off errors to be introduced with repeated operations. Suppose we have the following definition:
float Total = .1+.1+.1+.1+.1+.1+.1+.1+.1+.1;
The following expression, which is mathematically true, will not likely be true within the program.
Total == 1.0
Instead of directly testing for equality or inequality, we should check if the two values (from the above expressions) are sufficiently close to each other. This checking is done by specifying a maximum error tolerance and verifying that the absolute value of the difference is smaller than the tolerance. For example, suppose the maximum error tolerance is specified by the following constant:
Const float Delta = 0.0001;
There is a math library function, fabs(), that returns the absolute value of its floating point parameter. You can use this function to detect if the two values are sufficiently close as follows:
if (fabs(Total – 1.0) <= Delta) {…}
A value of True shows that the two values are sufficiently close.
Faulty While Assumption
Consider the following code:
int Position;
while (cin >> Position)
{
cout << “Extract another value” endl;
}
cout << “Last input: ” << Position;
“Newbies” often make the mistake of assuming that the body of the while loop is always executed at least once. It is important to realize that if the while loop initially comes back false, then its while body is never executed. For the above code, if there is no more data in the standard input stream before the code segment begins, then the insertion statement would display an object that has never been explicitly set.
Next: Function Basics and Libraries >>
More C++ Articles
More By Chrysanthus Forcha