0

I am very confused with c++ pointers and reference operators. My main confusion is the following (simple ) code:

#include <iostream>

using namespace std;

void changeInt(int &a)
{
    a *= 3;
}

int main()
{
    int n = 3;
    changeInt(n);
    cout << n << endl; 

    return 0;
}

Mainly, I am confused as to why changing the address (&a) changes the actual variable (n). When I first attempted this problem this was my code:

#include <iostream>

using namespace std;

void changeInt(int &a)
{
    *a *= 3;
}

int main()
{
    int n = 3;
    changeInt(n);
    cout << n << endl; 

    return 0;
}

But this gives me an error. Why is it that when I change the address it changes the variable, but when I change the value pointed by the address I get an error?

Asad-ullah Khan
  • 1,573
  • 18
  • 22

3 Answers3

3

Your second example is not valid C++, you can only dereference a pointer (or an object whose type overload operator*, which is not your case).

Your first example pass the parameter by reference (int &a is not "the address of a", it is a reference to a), which is why a change to a really is a change to the object being passed by the function (in you case, n)

quantdev
  • 23,517
  • 5
  • 55
  • 88
2

The ampersand (&) in that context means a reference, not the "address". E.g.:

int some_int;

int & a = some_int; // Declare 'a', a reference to 'some_int'

int * p = &some_int; // '&' in this context is "the address of" 'some_int'

A reference is equivalent to a pointer in many ways, but it behaves like a value type. See this thread and the wikipedia entry to learn more.

Community
  • 1
  • 1
glampert
  • 4,371
  • 2
  • 23
  • 49
1

The ampersand indicates that a variable is passed by reference to your function -- but inside the function the variable is treated as if it were passed by value. This is syntactic sugar, to make writing code that accepts references simpler to understand.

Drone2537
  • 525
  • 3
  • 12