Friday, July 14, 2017

About 'const' qualifier...

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change value of const variable by using pointer ). The result is implementation-defined if an attempt is made to change a const.

When we make some pointer as constant, its restricting the access to that memory location through that pointer variable only which means still you will be able to make any modification using other means.

#include

void main()
{
  int i=10, j=20;

  const int *p = &i;      // Pointer to a constant
  int * const p1 = &i;    // Constant pointer to an integer variable
  const int * const p2 = &j;  // Constant pointer to an integer constant 

  *p = NULL;

  p1 = NULL;

  *p2 = 25;

  i = 30;      // valid because we are accessing directly not through pointer

  printf("%d\n", p);
}

Linux 64-bit machine output:

const.c: In function `main':
const.c:10: error: assignment of read-only location
const.c:10: warning: assignment makes integer from pointer without a cast
const.c:12: error: assignment of read-only variable `p1'
const.c:14: error: assignment of read-only location'


Other easy way to remember is how the const keyword is assosiated in the variable declaration statement, as a prefix. const int * OR int const *  refers to value and (int * const ptr) refers to address. I mean, after the keyword const, is the value is there or address is there will be the actual constant (address or value). const int * const ptr where const is associated with both and hence both are constants.

Reference:
http://www.geeksforgeeks.org/const-qualifier-in-c/

No comments:

Post a Comment