0

Can you tell me the difference between the source 1 and 2? The book says the first one is call by address(pointer) and the second one is call by reference, but i don't exactly get those two sources. Please explain those sources to me please, thank you in advance.

1.

#include <iostream>
using namespace std;

void absolute(int *a);
void main()
{
    int a = -10;
    cout << "Value a before calling the main function = " << a << endl;
    absolute(&a);
    cout << "Value a after calling the main function = " << a << endl;
}
void absolute(int *a)
{
    if (*a < 0)
        *a = -*a;
}

2.

#include <iostream>
using namespace std;

void absolute(int &a);
void main()
{
    int a = -10;
    cout << "Value a before calling the main function" << a << endl;
    absolute(a);
    cout << "Value a after calling the main function" << a << endl;
}
void absolute(int &a)
{
    if (a < 0)
        a = -a;
}

1 Answers1

0

In terms of what happens at the CPU level, pointers and references are exactly the same. The difference lies in the compiler, it won't let you do a delete on a reference (and there's less typing)

So in your code both functions do the same thing.

James
  • 9,064
  • 3
  • 31
  • 49