0
How do assignment operators work?
And are they important? I'm a bit confused.
8 Antworten
0
What I mean is how does x=x+4 work?
How is that even possible?
0
assignment operators are used to assign(give)a variable a value
0
ex: int num=64;
0
64 is the assigned value
0
They are used to allow UDT (user defined types - also called Abstract Data Types (ADT) to act like built-in types, so that you can use them in the same convenient way you can use built-in types i.e.:
class C{/*overload assignment operator here*/};
C c1, c2;
c2 = c1;
Since you can also overload virtually all the operators (+,-*,/,++,=,+=,etc.), you can write code with your own types which is more readable and easier to reason about. This is a very powerful feature in C++.
Look at this link for an example how to overload pre-/post-increment as well as assignment operator. It should give you an idea how it is done:
https://code.sololearn.com/c4BgbEv35NSx/#cpp
0
Ok, so your question is how does x=x+4 work in the general case, not just in terms of class operator overloading (which is what I thought you asked)?
It may look a bit strange in the beginning when you consider x = x + 4 from a pure mathematical point-of-view. But you need to put your CS hat on!
For the statement x = x + 4 to even compile x needs to have been declared beforehand. Typically something like:
int x;
Declaring x like that means the compiler has allocated space in memory for x. This memory the compiler will allocate depends on the type of the variable - it is typically 4 bytes for an int on a 32bit OS (or 8 bytes on a 64bit OS).
But the key thing to grasp is that the compiler has allocated some memory for x. And this memory (lets say 4 bytes) is located at a specific address.
So back to assignment. Let say the code was this:
int x;
x = x + 4;
The way to look at it is to realize that the "right-hand" side (x+4) is computed 1st, and then the result is assigned to the "left-hand" side i.e. to x.
So what will x + 4 compute to? The compiler will generate the following code for that:
- Read value of x from 4 bytes allocated by the compiler.
- Store in one of the CPU registers
- Add 4 to the CPU register.
The CPU register now contain the "right-hand" side.
To do the assignment to the "left-hand" side, simply write the CPU register value (which is also 32 bits on a 32 bit system) back to the memory allocated for x. Voila! Done!
So what will the value of x be in the above case? It can literally be anything since we never initialized x. So whatever value was present in the 4 bytes allocated by the compiler for x (lets say 12852), 4 would have been added to that and assigned back to x i.e. x would be 12856.
I'm sure you would now be able to figure out what x would be for this case:
int x = 0;
x = x+ 4;
0
I THINK I get it...is it that you add 4 to the original value of x?
0
Yes, exactly!