c++ - `&` in function parameter list -


i saw in code , i'm confused 1 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 not valid (compiler error) } 

what purpose of & before val? @ first thought take address pointer (val point ptr_foo location) apparently doesn't.

also, why fun2(&foo) compile fun1(&foo) doesn't?

it declares parameter reference. parameter becomes in/out rather c++/c's normal in only.

this updates structure passed function.

 void fun1 (ptr_mystruct &val)  {     val = somevalue ;  } 

this updates copy of parameter in fun2 caller never sees change.

 void fun2 (ptr_mystruct val)  {     val = somevalue ;  } 

here fun2 expects pointer pointer structure. works

fun2(&foo); //this works fine 

here fun1 expects pointer structure , passing pointer pointer:

fun1(&foo); //this not valid (compiler error) 

imho, example has 1 level of indirection more needed fun1. need structure passed reference:

void fun1(mystrct &val) 

this you'd in olde days of c before references make structure read/write

void fun2(ptr_mystrct val) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -