Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is *p++ different from *p += 1?

Tags:

c

People also ask

What is the difference between * P and * p?

p is the value of p while *p is the value stored in the memory location pointed by p . When you want to indirectly access the value of an integer i , you can have an integer pointer point to it ( int *p = &i ) and use that pointer to modify the value of i indirectly ( *p = 10 ).

What is difference between a * p ++ and p ++ B P and * p?

Difference between ++*p, *p++ and *++p in C In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative.

Are expression * p ++ and ++* ptr are same?

3) Are the expression ++*ptr and *ptr++ are same? The correct option is (b). Explanation: ++*ptr increments the value pointed by ptr and*ptr++ increments the pointer not the value.

What does * p ++ do does it increment P or the value pointed by p?

Q: Does *p++ increment p, or what it points to? A: The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed to before p was incremented.


The key is the precedence of the += and the ++ operator. The ++ has a higher precedence than the += (in fact, assignment operators have the second lowest precedence in C), so the operation

*p++

means dereference the pointer, then increment the pointer itself by 1 (as usually, according to the rules of pointer arithmetic, it's not necessarily one byte, but rather sizeof(*p) regarding the resulting address). On the other hand,

*p += 1

means increment the value pointed to by the pointer by one (and do nothing with the pointer itself).


Precedence. The postfix ++ binds tighter than the prefix * so it increments p. The += is at the low end of the precedence list, along with the plain assignment operator, so it adds 1 to *p.