C++

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 number 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, NumMinutesToThink is added to NumMinutesToType, because these are in the innermost parentheses. Then this sum is multiplied by 60. Next, PeopleInTheOffice is 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. Add a comment at the top to explain what this code does, and change the 60 to a symbolic constant. You then will have code that is easy to understand and maintain.

DO remember that expressions have a value. DO use the prefix operator (++variable) to increment or decrement the variable before it is used in the expression. DO use the postfix operator (variable++) to increment or decrement the variable after it is used. DO use parentheses to change the order of precedence. DON’T nest too deeply, because the expression becomes hard to understand and maintain.

Back to Index