In this first example, with -=, this works as expected:
Image with result
int value = 3;
int *ptr = &value;
printf("%dn", ptr);
*ptr -= 1;
printf("%dn", ptr);
printf("%dn", value);
But in this other example, with –, the value of the pointer itself decrements, and the value of “value” stays the same:
Image with result
int value = 3;
int *ptr = &value;
printf("%dn", ptr);
*ptr --;
printf("%dn", ptr);
printf("%dn", value);
This is not a big deal of course, but I’m interested in hearing about the differences between two operations that many think are identical.
3
C’s operator precedence rules say that postfix decrement binds more tightly than pointer dereferencing, so *ptr--
means *(ptr--)
, not (*ptr)--
. If you write the latter, then it will do the same as -=
.
For reference:
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 | -- |
Suffix/postfix decrement | Left-to-right |
2 | * |
Indirection (dereference) | Right-to-left |
14 | -= |
Assignment by difference | Right-to-left |
4