Pass By Reference Question

Hi, I'm learning about pointers and references and came across these example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

void passByReference(int &x);
void passByReferenceTwo(int *x);

int main()
{
    int first = 13;
    int second = 13;

    passByReference(first);
    passByReferenceTwo(&second);
    cout << first << endl;
    cout << second << endl;

    return 0;
}

void passByReference(int &x){
    x = 66;
}
void passByReferenceTwo(int *x){
    *x = 54;
}


Both of these are working, my question is: Is one of them a better way than the other? Or are there some pros and cons with both of the ways?
The second is not a "by reference". It is actually "by value", but since the value happens to be of type pointer, the result resembles the by reference.

You cannot call by reference without having an object, but you can do passByReferenceTwo(0);
Therefore, the function should test that the pointer is not null before trying to use it.

This can be exploited. For example:
int toInt( const std::string & text, bool * ok );
You could call toInt:
int foo = toInt( word, 0 );
or:
1
2
3
4
5
bool ok = false;
int foo = toInt( word, &ok );
if ( ok ) {
  // foo is valid
}

From the user point of view there is no big difference; a reference 'ok' would be almost as fine,
but within the toInt the error reporting is done only if ok is non-null.


A pointer can be null, have an address, or have an address and by miracle the objects on consecutive memory locations happen to be of same type (i.e. there is an array). This makes pointer flexible, but on the other hand you cannot be as sure what you actually have. A reference is exact.
Topic archived. No new replies allowed.