How does a pointer declared with const keyword considered as a pointer to a constant

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • radha gogia
    New Member
    • Feb 2015
    • 56

    How does a pointer declared with const keyword considered as a pointer to a constant

    Code:
    #include<stdio.h>
    int main()
    {
        int x=3;
        int const *ptr =&x;
        printf("%d",++x);
        printf("\n %d",++*ptr);
        return 0;
    }
    I am unable to get that when x is a variable not a constant then how come the error is that the since ptr is a pointer to a constant hence we cannot change its value, although ++x works fine, whats the logic behind this ?

    just one confusion that why are we saying that ptr is a pointer to a constant when actually ptr is holding the address of a variable ?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    In your example x is an int. So ++x works fine. No mystery there.

    This code:

    Code:
    int const *ptr =&x;
    says that ptr is a pointer to a const int. This pointer contains the address of x.

    It doesn't matter whether x is const or not. As far as ptr is concerned, x is const because ptr is a pointer to a const int. Therefore, ptr cannot be used to change x.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      By the way,
      Code:
      int * const ptr = &x;
      Notice that this time const follows the asterisk (*). This means that ptr is a constant pointer to int. That is, you can change the value of the int that ptr points to, but you cannot change the value of ptr to make it point at a different int.

      Comment

      Working...