struct anup1 {
int a;
};
void structpass_1(struct anup1 b) // accepting structure
{
cout << b.a;
};
void structpass_2(struct anup1& b) // accepting address of a structure
{
cout << b.a;
};
int main() {
struct anup1 a2;
a2.a = 100;
structpass_1(a2);
structpass_2(a2);
}
The above code gives same output…whether accepting parameter is struct / address of struct.
Can anyone please explain to me this behavior?
Thanks
In
structpass_1your structureanup1is passed by value, so a local copy is done and passed to the function.Instead, in
structpass_2the structure is passedby reference, i.e. a pointer to the structure instance is passed to the function (you have pointer semantic but value syntax). No local copy of the whole structure is done.Note that for a simple structure containing only one integer passing by value or by reference is the same from a performance perspective. But when you have more complex (and bigger) data, passing by reference is more efficient.
An important difference between the two cases of passing by value vs. passing by reference is that if you modify the structure instance inside the function body, only if the structure is passed by reference the modifications are persistent at the call site. Instead, when you pass the structure by value, since a local copy is done inside the function body, the modifications are lost when the function exits. e.g.: