Post-increment on a dereferenced pointer?
Due to operator precedence rules and the fact that ++
is a postfix operator, add_one_v2()
does dereference the pointer, but the ++
is actually being applied to the pointer itself. However, remember that C always uses pass-by-value: add_one_v2()
is incrementing its local copy of the pointer, which will have no effect whatsoever on the value stored at that address.
As a test, replace add_one_v2()
with these bits of code and see how the output is affected:
void add_one_v2(int *our_var_ptr)
{
(*our_var_ptr)++; // Now stores 64
}
void add_one_v2(int *our_var_ptr)
{
*(our_var_ptr++); // Increments the pointer, but this is a local
// copy of the pointer, so it doesn't do anything.
}
This is one of those little gotcha's that make C and C++ so much fun. If you want to bend your brain, figure out this one:
while (*dst++ = *src++) ;
It's a string copy. The pointers keep getting incremented until a character with a value of zero is copied. Once you know why this trick works, you'll never forget how ++ works on pointers again.
P.S. You can always override the operator order with parentheses. The following will increment the value pointed at, rather than the pointer itself:
(*our_var_ptr)++;