Sunday 28 February 2016

Difference between constant pointer and pointer to constant

Constant pointer:

Declaration:
int *const ptr = &m;
Note: Apply the keyword from right to left.
Explanation: "ptr" is a constant pointer because keyword "const" will have higher precedence then "*" symbol.
Significance: The value of address can not be changed.
Example: ptr = &n; is not allowed because the memory location which "ptr" is pointing to, can not be changed.
Value or Data at address location can be changed.
Example: *ptr = 20.
Data at "*ptr"  has been modified to 20.

Pointer to constant.

Declaration:
int const *ptr = &m;
Note: Apply the keyword from right to left.
Explanation: "ptr" is a pointer which is pointing to constant integer data.
Significance: The value or data where pointer is pointing to, can not be changed.
Example:
*ptr = 20; is not allowed but "ptr = &n" is valid.

No comments:

Post a Comment