11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

42 Part I: Introduction to C++ ProgrammingAn unusual aspect of C++ is that an expression is a complete statement. Thus,the following is a legal C++ statement:1;The type of the expression 1 is int.Determining the Order of OperationsAll operators perform some defined function. In addition, every operator hasa precedence — a specified place in the order in which the expressions areevaluated. Consider, for example, how precedence affects solving the followingproblem:int var = 2 * 3 + 1;If the addition is performed before the multiplication, the value of the expressionis 2 times 4 or 8. If the multiplication is performed first, the value is 6 + 1or 7.The precedence of the operators determines who goes first. Table 3-1 showsthat multiplication has higher precedence than addition, so the result is 7.(The concept of precedence is also present in arithmetic. C++ adheres to thecommon arithmetic precedence.)So what happens when we use two operators of the same precedence in thesame expression? Well, it looks like this:int var = 8 / 4 / 2;But is this 8 divided by 2 or 4, or is it 2 divided by 2 or 1? When operators ofthe same precedence appear in the same expression, they are evaluated fromleft to right (the same rule applied in arithmetic). Thus, the answer is 8 dividedby 4, which is 2 divided by 2 (which is 1).The expressionx / 100 + 32divides x by 100 before adding 32. But what if the programmer wanted to dividex by 100 plus 32? The programmer can change the precedence by bundlingexpressions together in parentheses (shades of algebra!), as follows:x/(100 + 32)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!