C++ Programming Tips (Page 1 of 5 )
In this article, I give you programming tips that can improve your C++ code. I will cover use of parentheses, long expressions, modifying objects, and more. By the time I'm done, you will hopefully have learned a few ways to make your code faster as well as easier to understand and maintain.
C++ Fundamentals
Use of parentheses
Consider this expression without parentheses:
a * b + c / d – 4
and the equivalent with parentheses:
(a * b) + (c / d) – 4
Both expressions perform exactly the same computation, but the meaning of the second one is clearer, since parentheses are used.
Expressions (like the two above) are evaluated by following the rules of precedence. The above expressions are the same. So from a technical point of view, you do not need parentheses. However, including parentheses makes the order of evaluation explicit to the person maintaining your code (even you).
Long expressions (Style)
We often need to write long expressions that will not fit on one line of the screen. For example, the expression
cout << Mass << “grams of a hydrocarbonnwith “<< CarbonAtoms << “ carbon atom(s) and “
<< HydrogenAtoms << “ hydrogen atom(s)ncontains “ << Molecules << “molecules” << endl;
is quite long and will not fit on one line of the screen. A good way to break a long expression into a multiline expression is to use continuation lines. These lines should always begin with an operator and be indented one space. Both of these serve to signal the reader that the line is a continuation of the previous line. So the above example can be written as follows:
cout << Mass << “grams of a hydrocarbonnwith “<< CarbonAtoms
<< “ carbon atom(s) and “ << HydrogenAtoms << “ hydrogen atom(s)ncontains “
<< Molecules << “molecules” << endl;
As another example, the expression
((Xcoord1 – Ycoord1) / 2 ) * Distance1 + ((Xcoord2 – Ycoord2) /
2) * Distance2;
can be better written as
((XCoord1 – Ycoord1) / 2 ) * Distance1
+ ((Xcoord2 – Ycoord2) / 2) * Distance2;
Speed versus clarity and correctness
One rule of thumb in programming is that 90 percent of a program’s running time is spent on 10 percent of the code. So without some idea of where a program spends most of its time, most changes to a program to speed it up will have little or no effect on the overall running time. While speed is important, clarity (presentation of the code) and correctness are always more important. We should never sacrifice clarity and correctness for speed.
Hot spots are where a program spends most of its time. If speed becomes an issue, a more effective approach is to complete the writing of the program and then order a tool which can be used to identify the hot spots of the program. The hot spots can then be tuned (recoded) to reduce the running time of the program.
Next: Modifying Objects >>
More C++ Articles
More By Chrysanthus Forcha