Search code examples
c++pointersreturn

C++ Returning Pointers/References


I have a fairly good understanding of the dereferencing operator, the address of operator, and pointers in general.

I however get confused when I see stuff such as this:

int* returnA() {
    int *j = &a;
    return j;
}

int* returnB() {
    return &b;
}

int& returnC() {
    return c;
}

int& returnC2() {
    int *d = &c;
    return *d;
}
  1. In returnA() I'm asking to return a pointer; just to clarify this works because j is a pointer?
  2. In returnB() I'm asking to return a pointer; since a pointer points to an address, the reason why returnB() works is because I'm returning &b?
  3. In returnC() I'm asking for an address of int to be returned. When I return c is the & operator automatically "appended" c?
  4. In returnC2() I'm asking again for an address of int to be returned. Does *d work because pointers point to an address?

Assume a, b, c are initialized as integers as Global.

Can someone validate if I am correct with all four of my questions?


Solution

  • In returnA() I'm asking to return a pointer; just to clarify this works because j is a pointer?

    Yes, int *j = &a initializes j to point to a. Then you return the value of j, that is the address of a.

    In returnB() I'm asking to return a pointer; since a pointer points to an address, the reason why returnB() works is because I'm returning &b?

    Yes. Here the same thing happens as above, just in a single step. &b gives the address of b.

    In returnC() I'm asking for an address of int to be returned. When I return c is the & operator automatically appended?

    No, it is a reference to an int which is returned. A reference is not an address the same way as a pointer is - it is just an alternative name for a variable. Therefore you don't need to apply the & operator to get a reference of a variable.

    In returnC2() I'm asking again for an address of int to be returned. Does *d work because pointers point to an address?

    Again, it is a reference to an int which is returned. *d refers to the original variable c (whatever that may be), pointed to by c. And this can implicitly be turned into a reference, just as in returnC.

    Pointers do not in general point to an address (although they can - e.g. int** is a pointer to pointer to int). Pointers are an address of something. When you declare the pointer like something*, that something is the thing your pointer points to. So in my above example, int** declares a pointer to an int*, which happens to be a pointer itself.