user3029760
user3029760

Reputation: 185

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

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++;
}

Upvotes: 7

Views: 532

Answers (4)

Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

As per precedence of operators,

++ precedes *

Hence, it is executed as

value++ and * of it. Effectively, *(value++)

value++ will return you the address of value + (size of datatype pointed at) i.e. value + (size of int) in this case.

Unless your value is pointing to an array, you are probably picking up a garbage value and dereferencing it.

Upvotes: 1

Alexander Oh
Alexander Oh

Reputation: 25661

while not precisely the answer: from K&R C this is how memcopy can be implemented. if you understand the precedences that are happening you'll be able to answer your question yourself.

void *memcpy(char *ptr1, char *ptr2, size_t n) {
  void *ret = ptr1;
  while (n >0) {
    *ptr1++ = *ptr2++;
    n--;
  }
  return ret;
}

Upvotes: 0

P.P
P.P

Reputation: 121427

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

Upvotes: 2

kvanbere
kvanbere

Reputation: 3352

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

Upvotes: 7

Related Questions