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?
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
.