0
int const i = 10;
int *j = &i;
*j = 20;
printf("%d",i);

If i is constant shouldn't it not be changed even through pointers. If not what is the condition for it to not change?

Chirag Gupta
  • 64
  • 1
  • 9

2 Answers2

3

The compiler should emit a warning for this line: int *j = &i;. You make a non const qualified pointer point to a const qualified object.

When you later attempt to modify i via the j pointer, the behavior is undefined:

  • if i is writable, it may be modified, and this is what you observe.
  • but if you define i at the file scope, the compiler may locate it in a read-only segment and the attempt might fail with a segmentation fault.
  • anything else could happen, including a presidential meltdown.

Try compiling and running this program:

#include <stdio.h>

int const i = 10;

int main(void) {
    int *j = &i;
    *j = 10;
    printf("%d\n", i);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
2

You can change a const variable but the behavior is undefined.

Your compiler should warn about the loss of const in the following line,

int *j = &i;

So const works exactly like that, it just prevents you from accidentally changing a const variable because you would listen to your compiler and fix your code before using it.

You can't however, directly assign to i.

But through pointers you can always get rid of const. Whether the resulting behavior is defined or not, is something you should know before you do get rid of const, which is sometimes fine, however if you MUST do it, it probably means you have a design problem.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97