Pages

Friday, December 15, 2017

const behavior of a variable in C Programming Language

When you intend to not change the value of a variable you declare it as a const in C language.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
int c1()
{
  int *a;
  const int b;

  a=&amp;b;

  printf("*a=%d, b=%d\n",*a, b);
  
  *a = *a + 1;
  //b = b + 1; 

  printf("*a=%d, b=%d\n", *a, b);

//return ;
}

main()
{       
        printf("C=%d\n", c1());
}




If you execute 
  b = b + 1:
then the compiler complains:
c1.c:12:5: error: cannot assign to variable 'b' with const-qualified type 'const int'
  b = b + 1; 
  ~ ^
c1.c:5:13: note: variable 'b' declared const here
  const int b;
  ~~~~~~~~~~^

That's what is expected.
But if we declare a pointer variable and that points to the const variable, and you increment the "value" of what the pointer variable is pointing to, then the compiler does not complain. Why?

Using only 
  *a = *a + 1;
actually increments the value of b because it's same as *a.



Let's change the program slightly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
int c1()
{
  int *a;
  const int b;

  a=&b;

  printf("*a=%d, b=%d\n",*a, b);
  
  *a = *a + 1;
  //b = b + 1; 

  printf("*a=%d, b=%d\n", *a, b);

//return ;
}

main()
{       
        printf("C=%d\n", c1());

}

This time the compiler gives an error.

s1.c:11:6: error: read-only variable is not assignable
  *a = *a + 1;
  ~~ ^

So, the rational is if you use the const identifier, then you can't update it's value.



No comments: