function - C++ Basic concept regarding reference operator return type -
i need clear basic concept. code works fine. can explain me if function caldouble returning address (reference) of int why need use & operator further in main int *j = &caldouble(i); address (reference) of int? thanks.
int& caldouble(int x) { x = x*2; return x; } int main(int argc, char *argv[]) { int = 99; int *j = &caldouble(i); system("pause"); return exit_success; }
int& caldouble(int x)
doesn't return address, reference int
.
you need take address of reference able assign pointer.
note code invokes undefined behavior. because pass parameter value, copy of created inside function. return local variable reference, not legal.
i think confusion comes &
. can used in 2 ways:
- applied variable
&x
, takes address - when in declaration
int& x
, defines reference
a reference alias, different name variable.
int x = 0; int& y = x;
now, x
, y
refer same variable.
int* z = &x;
takes address of x
.
Comments
Post a Comment