I have done my research but could not find an answer to this question I have. It might be due to lack of my bad phrasing of queries, so I beg your pardon in advance if this has been answered elsewhere but I would like to understand this very much.
Inside my main function, if I create an integer with:
int myInt;
to store an integer, and then call a predefined function (myFunc) with:
myInt = myFunc();
1 2 3 4 5 6 7 8 9 10 11 12 13
int myFunc () {
int calculatedInt;
/* some important calculations
are calculated and ran here to
be stored in calculatedInt */
calculatedInt = 8; // as an example.
return calculatedInt;
}
My question:
- What exactly happens in computers memory?
- Does it store "8" in an address, then copy it
to another address and delete first one?
(since it falls out of scope after function terminates)
- Or does it store it once, in a single address, and
returns a pointer to it under the hood as if I had a
function that returns a pointer to an object
created inside the function via "new" keyword?
ex:
1 2 3 4 5 6 7 8 9 10
int* myFunc () {
int* calculatedInt = newint;
// .... .... ...
// Return the pointer pointing to a what calculatedInt points to.
return calculatedInt;
}
In above scenario calculatedInt the pointer is stored in "stack", and only once does a new int is created and stored in heap permenantly, and its address gets returned so if my above myInt was a pointer, it would be pointed to that.
Usually object code uses registers (more often register EAX or register pair EAX:EDX for Intel compatible processors) to return objects of such simple types as int or int *. So the object code simply stores the values in register in the memory occupied by the variable that is assigned to.