I saw this in some code and I'm confused about one thing:
struct mystrct {...};
typedef mystrct* ptr_mystrct;
void fun1(ptr_mystrct &val)
{...}
void fun2(ptr_mystrct val)
{...}
main()
{
mystrct foo;
ptr_mystrct ptr_foo = &foo;
fun1(ptr_foo);
fun2(&foo); //this works fine
fun1(&foo); //this is NOT valid (compiler error)
}
What is the purpose of &
before val
? At first I thought it will take the address to the pointer (val
will point to ptr_foo
location) but it apparently doesn't.
Also, why does fun2(&foo)
compile where fun1(&foo)
doesn't?
It declares the parameter as a reference. The parameter becomes in/out rather than C++/C's normal in only.
This updates the structure passed to the function.
This updates a copy of the parameter in fun2 so the caller never sees the change.
Here fun2 expects a pointer a pointer to a structure. Works
Here fun1 expects a pointer to a structure and you are passing a pointer to a pointer:
IMHO, this example has one level of indirection more than needed for fun1. This is what you really need for a structure passed by reference:
This is what you'd do in the olde days of C before references to make a structure read/write