As I understand, when we call a function, a memory block on stack part of memory of the program, gets allocated for the function call, and all the parameters are copied from the calling function into this memory block. But how does this work in case of pass by reference? is the address of the memory in the calling program is copied or is value copied? If nothing is getting copied then how is the function accessing the variable, when there is no value nor address in it's memory block on stack?
#include <iostream>
using namespace std;
void printIntRef(int &a) {
printf("REF: a is %d, a address is %p\n", a, &a);
}
void printInt(int a) {
printf("INT: a is %d, a address is %p\n", a, &a);
}
void printIntPointer(int *a) {
printf("POINTER: *a is %d, a is %p, a address is %p\n", *a, a, &a);
}
int main() {
int a = 5;
printf("a is %d, a address is %p\n", a, &a);
printIntRef(a);
printInt(a);
printIntPointer(&a);
return 0;
}
result:
a is 5, a address is 0x7fffea647024
REF: a is 5, a address is 0x7fffea647024
INT: a is 5, a address is 0x7fffea64700c
POINTER: *a is 5, a is 0x7fffea647024, a address is 0x7fffea647008
How could address of variable a
in the function printIntRef
be same as a
in the main
program? if a is a memory block on function's memory on stack
Aucun commentaire:
Enregistrer un commentaire