user12622894
user12622894

Reputation:

Pass by references?

In the code below, I do not understand the difference between the two versions. In both cases, I make a passage by reference, it seems to me (I think).

Moreover, I do not understand why version 2 works, because for what I understand for the moment, the sign & allows me to give the address of a variable, so when I put function_name(int &yourInt) I technically ask the user to enter the address of an int? So I should call it like function_name(&myInt)? But here we call the function like function_name(myInt) instead.

Version 1 :

int value(int tab[], int *valeur)
{
    for (int i = 0; i < 5; i++)
    {
        *valeur += tab[i];
    }
    return *valeur;
}

int main()
{
    int test = 0;
    int tab[10] = { 1,2,3,4,5};
    std::cout << value(tab, &test) << std::endl;
    std::cout << test;
}

Version 2 :

int value(int tab[], int &valeur)
{
    for (int i = 0; i < 5; i++)
    {
        valeur += tab[i];
    }
    return valeur;
}

int main()
{
    int test = 0;
    int tab[10] = { 1,2,3,4,5};
    std::cout << value(tab, test) << std::endl;
    std::cout << test;
}

Upvotes: 2

Views: 108

Answers (2)

Henry Le Berre
Henry Le Berre

Reputation: 910

When the & character is part of a type declaration, it means that variable is a reference to another. So in the second function, int &valeur declares a variable named valeur that is a reference to an int. This example should help you understand:

#include <iostream>
int main() {
  int a = 5;
  int& b = a; // b is a reference to a
  std::cout << a << '\n'; // outputs 5
  std::cout << b << '\n'; // outputs 5
  a = 7;
  std::cout << a << '\n'; // outputs 7
  std::cout << b << '\n'; // outputs 7
}

As a result, you can simply call your second function with value(tab, test) which passes the test variable by reference.

Upvotes: 1

Tom Gebel
Tom Gebel

Reputation: 805

In the first example, value takes a pointer to int as second parameter. A pointer is used to save a memory address, so the function has to be called using the address operator (&), passing the address of test.

In the second example, value takes a non-const reference to int as second parameter, so you do not need to pass the memory address of test this time. What happens is almost equivalent to something like this:

int test = 0;
int& valeur = test;

So remember, the address operator:

int test;
std::cout << &test; // outputs address of "test" in memory

is not the same as a reference, which is part of the type of a variable:

int test;
int& valeur = test; // here, the type of "valeur" is "int&"

Upvotes: 0

Related Questions