More Assignment Operators: , -, , ,

I l @ ve RuBoard

More Assignment Operators: +=, -=, *=, /=, %=

C has several assignment operators. The most basic one, of course, is = , which simply assigns the value of the expression at its right to the variable at its left. The other assignment operators update variables . Each is used with a variable name to its left and an expression to its right. The variable is assigned a new value equal to its old value adjusted by the value of the expression at the right. The exact adjustment depends on the operator, for example,

scores += 20 is the same as scores = scores + 20
dimes -= 2 is the same as dimes = dimes - 2
bunnies *= 2 is the same as bunnies = bunnies * 2
time /= 2.73 is the same as time = time / 2.73
reduce %= 3 is the same as reduce = reduce % 3

In the preceding list, we used simple numbers on the right, but we could have used more elaborate expressions:

 x *= 3 * y + 12    is the same as   x = x * (3 * y + 12) 

The assignment operators we've just discussed have the same low priority that = does, that is, less than that of + or * . This low priority is reflected in the last example, in which 12 is added to 3 * y before multiplying the result by x .

You are not required to use these forms. They are, however, more compact, and they may produce more efficient machine code than the longer form. The combination assignment operators are particularly useful when you are trying to squeeze something complex into a for loop specification.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net