Call by reference in C ++

What is actually passed in the call through a function reference?

void foo(int &a,int &b)

when I write

foo(p,q)

what is actually passed to the function. Is this the address of p and q?

+3
source share
5 answers

What is actually passed to the function is a link. The named parameter bbecomes a synonym for the argument object q.

, , , q , b. , " " , ++, , . , , , , (). , .

, , , " ", , . , char 4- , , " int". , " ".

+6

.

, - , - . , .

SO: ?

+3

- , . . , , , , . Wikipedia .

+2

, , , .

"" , . - . .

:

int foo(int& a, int& b) { a = b; }

// Usage
int x, y;
foo(x, y);

, :

int foo(int* a, int* b) { *a = *b; }

// Usage
int x, y;
foo(&x, &y);

, ( ).

, , , . :

void foo(int& x) { std::cout << &x << std::endl; }

int y;
std::cout << &y << std::endl;
foo(); // This will print the same as above.
+1

. int&, ++. :

int x = 10;
int& y = x;
x = 100;

, y? , . , int&, .

:

void byRef(int& x)
{
    return;
}

void byVal(int x)
{
    return;
}

void byPtr(int * x)
{
    return;
}

int _tmain(int argc, _TCHAR* argv[])
{

    int x = 0;
    byRef(x);
    byVal(x);
    byPtr(&x);

    return 0;
}

MSVC90, byRef byPtr, :

lea eax, [x]
push eax
call byRef ;or byPtr
add esp, 4
0

Source: https://habr.com/ru/post/1735988/


All Articles