L13 Assignment Ops
L13 Assignment Ops
Topics
Increment and Decrement Operators
Assignment Operators
Debugging Tips
Reading
Sections 3.11 - 3.12
Increment Operator
If we want to add one to a variable, we can say:
count = count + 1 ;
Programs often contain statements that
increment variables, so to save on typing, C
provides these shortcuts:
count++ ; OR ++count ;
Both do the same thing. They change the value
of count by adding one to it.
Postincrement Operator
The position of the ++ determines when the value is
incremented. If the ++ is after the variable, then the
incrementing is done last (postincrementation).
int amount, count ;
count = 3 ;
amount = 2 * count++ ;
Preincrement Operator
If the ++ is before the variable, then the incrementing is
done first (preincrementation).
int amount, count ;
count = 3 ;
amount = 2 * ++count ;
1 gets added to count first, then amount gets the value of
2 * 4, which is 8.
So, after executing the last line, amount is 8 and count is
4.
Postdecrement Operator
The position of the -- determines when the value is
decremented. If the -- is after the variable, then the
decrementing is done last (postdecrementation).
int amount, count ;
count = 3 ;
amount = 2 * count-- ;
Predecrement Operator
If the -- is before the variable, then the decrementing is
done first (predecrementation).
int amount, count ;
count = 3 ;
amount = 2 * --count ;
Practice
Given
int a = 1, b = 2, c = 3 ;
++a * b - c--
More Practice
Given
int a = 1, b = 2, c = 3, d = 4 ;
++b / c + a * d++
Expression Value
i += j + k
j *= k = m + 5
k -= m /= j * 2