I understand that for it to works it needs to be
void increment(int *value)
{
(*value)++;
}
This is because it needs brackets due to how precedence works (correct me if i'm wrong). But how come when I do the following, no compile error happens? The value isn't changed which is to be expected because there are no brackets, but what exactly is this changing?
void increment(int *value)
{
*value++;
}
Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type.
A pointer can be incremented by value or by address based on the pointer data type. For example, an integer pointer can increment memory address by 4, since the integer takes up 4 bytes.
No, it's not OK to increment an array. Although arrays are freely convertible to pointers, they are not pointers.
value
is a pointer to an integer. The rules of pointer arithmetic say that if you do an operation like value++
, then afterwards it will point to value + sizeof(int)
(in terms of bytes).
What's happening here is you would be dereferencing value
to get some rvalue which you just throw away, and then incrementing value
(not the thing it's pointing to, rather, the pointer itself).
*value++;
It's de-referencing the value at the location pointed to by value
and increments the pointer value
due to post-increment. Effectively, it same as value++
since you are discarding the value returned by the expression.
But how come when I do the following, no compile error happens?
Because it's a valid statement and you are just discarding the value returned by the expression. Same way, you could have statements like:
"Random string";
42;
and they are valid and would compile fine (but useless).
We discard a lot of standard library functions' return values. E.g. memset()
returns void *
to the memory that was set but we rarely use it. This is not so intuitive, but it's perfectly valid.
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