Sams Teach Yourself C++ in 21 Days

(singke) #1

Nesting Parentheses ..............................................................................................


For complex expressions, you might need to nest parentheses one within another. For
example, you might need to compute the total seconds and then compute the total num-
ber of people who are involved before multiplying seconds times people:
TotalPersonSeconds = ( ( (NumMinutesToThink + NumMinutesToType) * 60) *
(PeopleInTheOffice + PeopleOnVacation) )
This complicated expression is read from the inside out. First,NumMinutesToThinkis
added to NumMinutesToTypebecause these are in the innermost parentheses. Then, this
sum is multiplied by 60. Next,PeopleInTheOfficeis added to PeopleOnVacation.
Finally, the total number of people found is multiplied by the total number of seconds.
This example raises an important related issue. This expression is easy for a computer to
understand, but very difficult for a human to read, understand, or modify. Here is the
same expression rewritten, using some temporary integer variables:
TotalMinutes = NumMinutesToThink + NumMinutesToType;
TotalSeconds = TotalMinutes * 60;
TotalPeople = PeopleInTheOffice + PeopleOnVacation;
TotalPersonSeconds = TotalPeople * TotalSeconds;
This example takes longer to write and uses more temporary variables than the preceding
example, but it is far easier to understand. If you add a comment at the top to explain
what this code does and change the 60 to a symbolic constant, you will have code that is
easy to understand and maintain.

78 Day 4


DOremember that expressions have a
value.
DOuse the prefix operator (++variable)
to increment or decrement the variable
before it is used in the expression.
DOuse the postfix operator (variable++)
to increment or decrement the variable
after it is used.
DOuse parentheses to change the order
of precedence.

DON’Tnest too deeply because the
expression becomes hard to understand
and maintain.
DON’T confuse the postfix operator with
the prefix operator.

DO DON’T

Free download pdf