pointer confusion

I thought i grasped pointers, but when i go to actually use them, low and behold, apparently i do not. I was trying to understand the difference of reference and pointers, and the purpose behind them as obviously references are easier to comprehend and use.

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
26
#include <iostream>

int value_add(int n){
    n++;
    return n;
}

void reference_add(int &n){
    n++;
}

void pointer_add(int *n){
    *n++;
}

int main(){
    int num = 0;
    std::cout << num << std::endl;
    num = value_add(num);
    std::cout << num << std::endl;
    reference_add(num);
    std::cout << num << std::endl;
    pointer_add(&num);
    std::cout << num << std::endl;

}

1
2
3
4
0
1
2
2

I was expecting num to be incremented like the others and last num be 3
Last edited on
*n++; doesn't do what you think. It is interpreted as *(n++);. Put parentheses like this (*n)++; and you will get the expected result.
aaah, ok. Thanks, i will have to remember that when using the inc/dec operators. Wouldnt it just be simpler to say:
*n += 1;?

OK in this situation, why would you use pointers? As its more complicated, more syntax required, more error prone? When reference is just one extra syntax required and does it at the same speed without copying?
Last edited on
> Wouldnt it just be simpler to say: *n += 1;?

Or ++*n ;
In general, prefer the prefix incrememt or decrement operators if you do not need to make a copy of the object before it was modified.


> in this situation, why would you use pointers?

In general, use pass by pointer when an object may or may not be there:
template < typename T > void foo( T* pointer ) ; // pointer may be null

Use pass by reference when an object will always be there:
template < typename T > void foo( T& reference ) ; // reference refers to an object
Topic archived. No new replies allowed.