These operators will allow us to 'save' code, ie write less.
Obviously, we programmers are not lazy. We are just efficient, ok?
Assignment Operators
We have sometimes used expressions like:x = x + 1;
This means "make variable x its old value plus 1".
However, this can be abbreviated to:
x += 1;
It means the same thing.
If we want to subtract y from x, we can do:
x = x - y;
Or more simply:
x -= y;
To make x receive the product value of x by y:
x = x * y;
Or in a lazier way:
x *= y;
The same goes for division and rest of division (module):
x /= y; is the same as x = x / y;
x %= y; is the same as x = x% y;
Very simple, no? Just one way to write less.
Increment and Decrement Operators
Do you think:x + = 1;
x = 2;
Is it writing little?
There are two ways to do this for each expression:
x ++ or ++ x
x-- or --x
If we use these expressions alone:
x ++; and ++ x;
x--; and --x;
They will have the same effect: increment in the first case and decrement in the second case by one unit.
The variations: ++ x and x ++ are called preincrement and postincrement
The variations: --x and x-- are called pre-decrement and post-decrement.
They work as follows ... suppose the expression:
y = x++;
Two things happen in that order:
- y gets the value of x
- x is incremented by one unit
Already in the expression:
y = ++ x;
The following occurs:
- x value is incremented by one unit
- y gets new x value, incremented
See the following program. What prints on the screen?
#include <iostream> using namespace std; int main() { int x=1; cout << x++; return 0; }The answer is 1. First print x, then increment x.
Put another cout for you to see the new x value later.
And the following program, which output will have?
#include <iostream> using namespace std; int main() { int x=1; cout << ++x; return 0; }Now yes, directly prints 2.
First the increment (++) occurs, and only then the value of x is printed.
Now let's look at another sequence of operations:
x = 2;
y = 3;
z = x * ++y;
What are the values of x, y and z after these three procedures?
Come on.
First, y is incremented to 4.
So we have z = x * y = 2 * 4 = 8
The new values are 2, 4 and 8.
Now let's look at this sequence of operations:
x = 2;
y = 3;
z = x * y--;
The value of z is: z = x * y = 2 * 3 = 6
Since the decrement sign came after the variable y, only then is it decremented to become 2. The new values are 2, 2, and 6.
No comments:
Post a Comment