I cannot explain the output of the program. ++ has an higher precedence than *, but how can you explain the following output, especially the last two lines:
http://en.cppreference.com/w/c/language/operator_precedence
This link says that postfix ++ has an higher precedence than * operator. But on line 6 why isn't the postfix ++ operation is done firsts and then dereferenced by * operator? I thought it should print 44...
#include <iostream>
struct pointer
{
pointer( int* p ) : ptr(p)
{
std::cout << "pointer initially points to " << ptr << " (value there:" << *ptr << ")\n\n" ;
}
pointer operator++(int)
{
std::cout << "step " << ++step << ". evaluate postfix ++\n" ;
std::cout << "\tbefore increment, pointer points to " << ptr << " (value there:" << *ptr << ")\n" ;
constauto old_value = *this ; // make a copy of the value before increment
++ptr ; // increment
std::cout << "\tafter increment, pointer points to " << ptr << " (value there:" << *ptr << ')'
<< "\n\tpostfix ++ returns a prvalue (value of pointer before the increment) " << old_value.ptr
<< " (value there:" << *old_value.ptr << ")\n\n" ;
return old_value ; // return the copy of the value before increment
}
int& operator*()
{
std::cout << "step " << ++step << ". dereference pointer pointing to " << ptr << " (value there:"
<< *ptr << ")\n\treturn reference to int with value " << *ptr << '\n' ;
return *ptr ;
}
int* ptr ;
int step = 0 ;
};
int main()
{
int a[3] = { 22, 44, 66 };
pointer p = a ;
std::cout << "evaluate *p++\n===============\n\n" ;
*p++ ;
}
pointer initially points to 0x7fff51076248 (value there:22)
evaluate *p++
===============
step 1. evaluate postfix ++
before increment, pointer points to 0x7fff51076248 (value there:22)
after increment, pointer points to 0x7fff5107624c (value there:44)
postfix ++ returns a prvalue (value of pointer before the increment) 0x7fff51076248 (value there:22)
step 2. dereference pointer pointing to 0x7fff51076248 (value there:22)
return reference to int with value 22