Reputation: 19
#include<stdio.h>
void main ()
{
int a=4;
const int *p=&a;
*p--;
}
in the above line it means that we can not change the value a via p, so in decrement statement it should give an error but it is not giving the error. can anyone explain why??
Upvotes: 0
Views: 61
Reputation: 7429
You're probably getting the order wrong in which the operators happen. Postfix decrement got a higher operator precedence than the dereference. So you got:
*(p--);
which doesn't give an error since the value pointed to by the const pointer doesn't get modified. It's undefined behaviour though and anything can happen since you're dereferencing an invalid pointer.
Upvotes: 2
Reputation: 53376
*p--
decrements p
not contents of p
.
If you do (*p)--
you will get compilation error
error: decrement of read-only location ‘*p’
Upvotes: 5