0
#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??

  • 3
    `*p--` decrements `p` not contents of `p`. – Rohan Apr 23 '15 at 09:25
  • 1
    study about operator precedence. – mfro Apr 23 '15 at 09:27
  • It does provide run time error – Quantum_VC Apr 23 '15 at 09:29
  • possible duplicate of [const variable value is changed by using a pointer](http://stackoverflow.com/questions/18416733/const-variable-value-is-changed-by-using-a-pointer) – dhein Apr 23 '15 at 09:29
  • yep, and that's because you're using pointer to constant, by saying `*p--` you are actually changing the memory address your pointer is pointing to and not the content of that memory address, and hence the compiler isn't complaining. (as said by experts in answers posted) – manish Apr 23 '15 at 09:44

2 Answers2

5

*p-- decrements p not contents of p.

If you do (*p)-- you will get compilation error

error: decrement of read-only location ‘*p’
Rohan
  • 52,392
  • 12
  • 90
  • 87
2

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.

AliciaBytes
  • 7,300
  • 6
  • 36
  • 47