Sunday, March 21, 2010

Constant Pointer Vs Pointer Constant

Do you think that the terms Pointer Constant and Constant Pointer are the same?


If your answer is 'YES' then I can Prove it wrong through The below example...!



int main()
{
int i=2;
int const *p;
p=&i;
printf("%d",*p);
return 0;
}

int main()
{
int i=2;
int *const p=&i;
*p=3;
printf("%d",*p);
return 0;
}

OUTPUT:






2

3


Logic:

Constant Pointer:

Syntax: datatype const *ptr
  • In case of a Constant Pointer , the value remains constant where the address can be varied.
  • In case you provide any modification in the value it will result in an error.

  • Pointer Constant:

    Syntax: datatype *const ptr
  • Incase of a Pointer Constant Address remains constant.
  • Pointer must be initialized (i.e., int *const p=&i)
  • If you modify the address, it will result in an error where as you can modify the value of the pointer.


  • NOTE:
    In const *p , *p points value so value is constant.
    In *const p, p points address so address is costant.

    But the following programs make error:




    int main()
    {
    int i=2;
    int const *p;
    p=&i;
    *p=3
    printf("%d",*p);
    return 0;
    }

    int main()
    {
    int i=2,j;
    int *const p=&i;
    p=&j;
    printf("%d",*p);
    return 0;
    }

    0 comments:

    Post a Comment