Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I do *value++; to increment one to the value in that memory location?

Tags:

c++

pointers

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++;
}
like image 372
user3029760 Avatar asked Dec 03 '13 11:12

user3029760


People also ask

Can you add one to a pointer?

Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type.

Is it always possible to increment or decrement a pointer variable?

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.

Can we increment base address of array?

No, it's not OK to increment an array. Although arrays are freely convertible to pointers, they are not pointers.


2 Answers

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).

like image 115
kvanbere Avatar answered Sep 20 '22 10:09

kvanbere


*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.

like image 20
P.P Avatar answered Sep 18 '22 10:09

P.P