U
U
unclechu2014-07-07 22:07:20
C++ / C#
unclechu, 2014-07-07 22:07:20

"C": increment and pointer?

I ran into a bug that took a long time to debug. I would like to clarify for myself.
Can anyone explain what is the difference between these two lines?
(*i)++;
*i++;
UPD
Context:

int32_t i = 0;
void inc(int32_t *i) { (*i)++; }
void main() { inc(&i); }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Misha Krinkin, 2014-07-07
@unclechu

The first option increments the value pointed to by the pointer, and the second option increments the pointer itself.
UPD. Just add printf(PRId32 "\n", i) to your main and see the difference.

L
lookid, 2014-07-07
@lookid

Nothing. Pointer dereference will always be done before ++

F
Fil, 2014-07-08
@Fil

I'll add a little. The post-increment actually has a higher priority, so *p++ will execute ++ first. But this operation is tricky and not equivalent to +=1. To implement similar logic in their classes (C++), they do something like this:

A::operator++(int) { //Постфиксный 
  A temp(*this);
  *this+=1;
  return temp;
}

That is, a copy is returned, on which further operations are performed in the expression, although the object itself has already been increased.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question