Call by value VS call by reference C++ address understanding

186 Views Asked by At

So i am currently taking a course called data structures and algorithms, and for the first lesson i got a question that i can't quite rap my head around.. The teacher is trying to demonstrate the values of using a call by value and call by reference. He is passing a data struct to a function that prints the addresses of the data struct.

The code is basically this:

struct Exempelstruct{
    int m_intValue1;
    int m_intValue2;
    float m_array[1000];
};

void skrivAdresser1(Exempelstruct theStruct){
    writeAdresses( theStruct );
}
//and
void skrivAdresser2(const Exempelstruct &theStruct){
    writeAdresses( theStruct );
}

The question is why the addresses in the skrivAdresser1() function lower than the addresses that are printed by skrivAdresser2()?

2

There are 2 best solutions below

0
piyush172 On

Basically, you need to study the working of call by value and call by reference.

In call by value, the function copies the actual value of an argument into the formal parameter of the function. So the address of the formal parameter will obviously be different from that of the actual value(It may be greater or less whichever address is empty).

In call by reference, the actual value is passed through & So it has to same as that of the original value.

2
Kao On

Struct in skrivAddresser1 is constructed later, while the struct in skrivAddresser2 is the same as in the main which is created earlier. Cause main called earlier. The rule for stack variables is later the creation lower the address. So it does not matter which one you call earlier in main, because skrivAddress2 does not create a new object. And the original object is always created before calling skrivAddress functions.