I'm trying to relate C++ reference to pointer -


before saying duplicate question , downvote (as happened before), searched , found nothing alike.
i, many others, trying learn uses of c++ reference variables , relate them pointers. found easier make table , need know whether needs amended.

                   int *n   int n    int &n    caller/local void foo(int *n)     n       &n        &n          caller void foo(int n)     *n        n         n           local void foo(int &n)    *n        n         n          caller 

the table wants reflect legal passed parameters.

[1,1]: passing reference (trivial)   [1,2]: passing reference   [1,3(1)]: passing reference, an address(?)   [1,3(2)]: passing reference, n used alias(?)   [2,1]: passing value, dereferencing   [2,2]: passing value (trivial)   [2,3(1)]: passing value, using value of n (where n alias)   [2,3(2)]: passing value (dereferencing n, address)   [3,1(1)]: passing reference, foo accepts address   [3,1(2)]: passing reference, reference of value @ address n   [3,2(1)]: passing reference (trivial)   [3,2(2)]: passing reference, foo accepts address or reference   [3,3]: passing reference (trivial, argument matches parameter exactly)   
  1. are table , explanations correct?
  2. are there cases left out of table (except derived ones *&n, pointer pointer etc.)?

a function

void foo(int& n); 

does not accept address (a pointer), , not literals either.

so can't call like

int = ...; foo(&a);  // trying pass pointer function not taking pointer 

or

foo(1);  // passing r-value not allowed, can't have reference literal value 

there exception though, if have constant reference, like

int foo(const int& n); 

then literal values allowed, because referenced value can't changed.


likewise for

void foo(int* n); 

you must pass pointer.

so example:

int = ...; int& ra = a;   // ra references  foo(&a);  // ok foo(&ra); // ok foo(a);   // fail, not pointer foo(ra);  // fail, ra not pointer foo(1);   // fail, literal 1 not pointer 

and last:

void foo(int n); 

with examples:

int = ...; int& ra = a;   // ra references int* pa = &a;  // pa points  foo(a);   // ok, value of copied foo(ra);  // ok, value of referenced variable copied foo(*pa); // ok, dereferences pointer, , value copied foo(pa);  // fail, passing pointer function not expecting pointer foo(1);   // ok, literal value 1 copied 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -