I have an int
pointer (i.e., int *count
) that I want to increment the integer being pointed at by using the ++
operator. I thought I would call:
*count++;
However, I am getting a build warning "expression result unused". I can: call
*count += 1;
But, I would like to know how to use the ++
operator as well. Any ideas?
Try using (*count)++ . *count++ might be incrementing the pointer to next position and then using indirection (which is unintentional).
Pointer Arithmetic Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type.
Pointer arithmetic and arrays. Add an integer to a pointer or subtract an integer from a pointer. The effect of p+n where p is a pointer and n is an integer is to compute the address equal to p plus n times the size of whatever p points to (this is why int * pointers and char * pointers aren't the same).
The ++ has equal precedence with the * and the associativity is right-to-left. See here. It's made even more complex because even though the ++ will be associated with the pointer the increment is applied after the statement's evaluation.
The order things happen is:
You get the warning because you never actually use the dereferenced value at step 2. Like @Sidarth says, you'll need parenthesis to force the order of evaluation:
(*ptr)++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With