|
|
|
|
|
|
|
but you can't legally write |
|
|
|
|
|
|
|
|
35 = x; // error, not an l-value! |
|
|
|
|
|
|
|
|
New Term: An l-value is an operand that can be on the left side of an expression. An r-value is an operand that can be on the right side of an expression. Note that all l-values are r-values, but not all r-values are l-values. An example of an r-value that is not an l-value is a literal. Thus, you can write x = 5;, but you cannot write 5 = x;. |
|
|
|
|
|
|
|
|
There are five mathematical operators: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). |
|
|
|
|
|
|
|
|
Addition, subtraction, and multiplication act pretty much as you might expect. Not so with division. |
|
|
|
|
|
|
|
|
Integer division is somewhat different from everyday division. When you divide 21 by 4, the result is a real number (a number with a fraction). Integers don't have fractions, and so the remainder is lopped off. The value returned by 21 / 4 is 5. |
|
|
|
|
|
|
|
|
The modulus operator (%) returns the remainder value of integer division. Thus 21 % 4 is 1, because 21 / 4 is 5 with a remainder of 1. |
|
|
|
|
|
|
|
|
Surprisingly, finding the modulus can be very useful. For example, you might want to print a statement on every 10th action. |
|
|
|
|
|
|
|
|
It turns out that any number % 10 will return 0 if the number is a multiple of 10. Thus 20%10 is zero. 30%10 is zero. |
|
|
|
|
|
|
|
|
Combining the Assignment and Mathematical Operators |
|
|
|
|
|
|
|
|
It is not uncommon to want to add a value to a variable and then to assign the result back into the variable. If you have a variable myAge and you want to increase the value by two, you can write |
|
|
|
|
|
|
|
|
int myAge = 5;
int temp;
temp = myAge + 2; // add 5 + 2 and put it in temp
myAge = temp; // put it back in myAge |
|
|
|
|
|
|
|
|
This method, however, is terribly convoluted and wasteful. In C++ you can put the same variable on both sides of the assignment operator, and thus the preceding becomes |
|
|
|
|
|