0

I know how to do call by reference and call by pointer operations. But I am confused about doing both of them in pre and post-increment operation. Here the code snippet.

Call by reference with pointer arguments

void fun2(int *x) // It works like int *x=&x;
{
    ++*x;  // *x++ does not provide lvalue, so will not work here [ I think So ]
}

Call by reference with reference arguments

void fun3(int& x)
{
    ++x;  // x++; [both works fine but I can't understand why?]
}

Here's the Driver code

int main()
{
    int x=10;
    cout<<x<<"\n"; //10
    fun2(&x);
    cout<<x<<"\n"; //11
    fun3(x);
    cout<<x<<"\n"; //12
    return 0;
}

Why in fun2() *x++ gives the output 10 instead of giving 11 but ++*x works fine and in fun3() both x++ and ++x works fine?

walnut
  • 21,629
  • 4
  • 23
  • 59
Sumon Dey
  • 3
  • 2
  • Sorry while asking here I mistyped it. No, while writing code I write it fine void fun3(int &x). But don't know why call-by-pointer *x++ not changing the value of x – Sumon Dey Jan 12 '20 at 04:58
  • See the linked duplicate. It is about C (I am still trying to find a good C++ duplicate.) but it applies exactly the same to C++. – walnut Jan 12 '20 at 05:00
  • See this question https://stackoverflow.com/questions/18481740/pointer-expressions-ptr-ptr-and-ptr – samnaction Jan 12 '20 at 05:02
  • Thank you, That's exactly what I'm asking. – Sumon Dey Jan 12 '20 at 05:03
  • Does this answer your question? [Pointer expressions: \*ptr++, \*++ptr and ++\*ptr](https://stackoverflow.com/questions/18481740/pointer-expressions-ptr-ptr-and-ptr) – samnaction Jan 12 '20 at 05:07

1 Answers1

0

In fun2(), *x++ does not do what you think it does.

Per operator precedence, the ++ postfix increment operator has a higher precedence than the * dereference operator. As such, the statement *x++ is treated as *(x++), incrementing the pointer before then dereferencing it. The value being pointed at is untouched.

For what you are expecting, you need to use (*x)++ instead, dereferencing the pointer and then incrementing the value being pointed at.

You don't have the same problem with ++*x because the ++ prefix increment operator has the same precedence as the * dereference operator but is evaluated first, so ++*x is treated as ++(*x).

In func3(), there is no pointer to dereference. x is a reference to the caller's int (x in main()), and so both increment operators are being invoked directly on that int.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770