2

I understand calling foo(value) fine, but how does calling foo(*p) produce the same results? I thought it would error, but it works just fine.

*p is dereferencing the pointer, getting the value at address stored in p, so isn't it equivalent to calling foo(5)?

void foo(int &ptr)
{
    ptr = 6;
}

int main()
{
    using namespace std;
    int value = 5;
    int *p = &value;
    cout << "value = " << value << '\n';
    foo(*p);
    cout << "value = " << value << '\n';
    return 0;
}
3
  • 3
    Define "but it works just fine. " Commented Mar 7, 2016 at 0:17
  • 1
    Same reason you can do *p = 7; Commented Mar 7, 2016 at 0:33
  • Yes, *p gets the value that p points to. But you pass that value by reference, so the function gets a reference to the value that p points to. Commented Mar 7, 2016 at 0:51

2 Answers 2

1

First, when you dereference your pointer p, you get an integer value (because you declare it as a pointer to an integer). In this case, dereferencing p gets you the, er, value of your 'value' variable. With me so far?

So now, what happens in the function call? The program dereferences the pointer p, and then passes an lvalue reference to your variable (value) to the function. The function is defined to take a reference (a pointer with some syntactic sugar). So yes, you are correct in thinking it is dereferenced to an integer. However, C++ passes the address of the value variable anyway, rather than an integer variable, because you've told it to only accept references in the function.

Sign up to request clarification or add additional context in comments.

Comments

1

* operator used for dereferencing pointer returns lvalue just like identifier that stands for variable such as value, which is a primary expression. So both of them will be accepted for reference arguments.

Quote from N3337 5.1.1 General (5.1 Primary expressions):

8 An identifier is an id-expression provided it has been suitably declared (Clause 7). [...] The type of the expression is the type of the identifier. The result is the entity denoted by the identifier. The result is an lvalue if the entity is a function, variable, or data member and a prvalue otherwise.

Quote from N3337 5.3.1 Unary operators:

1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T,” the type of the result is “T.”

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.