-3

My question is why does the value of variable a changes, although I've declared it as const? Sorry if this is a trivial question.

const int a = 8;
int* ptr = &a;

printf("variable: %d \n", a);
printf("pointer: %d \n", *ptr);

*ptr = 1;
printf("pointer: %d \n", *ptr);
printf("variable: %d \n", a);

Output: 8 8 1 1

Thanks and have a nice day!

Avio
  • 21
  • 1
  • 1
  • 3
  • So you ask why the code riots if **you** break a contract **you** guaranteed? But your compiler should have warned, any reason you ignored that? Note: C does not have symbolic constants other than _enum-constants_. – too honest for this site Oct 29 '16 at 15:37
  • Generally speaking, the C-language standard does permit casting from 'pointer to const' to 'pointer to non-const', so the exact behavior of the program during runtime is undefined. More specifically, the runtime behavior of this program is compiler-dependent. If the compiler allocates const variables at a read-only segment of the executable image, then you will get a memory-access violation (aka *segmentation fault*) when the line `*ptr = 1` is executed. If it allocates them at a read-write segment of the executable image, then this line will be executed successfully. – barak manos Oct 29 '16 at 15:50

1 Answers1

0

You have qualified a as const, but when you assign its address to a pointer, this discards the effect of const and a can be now manipulated easily using ptr. This most likely invokes an undefined behaviour.

GCC will show a warning when you compile your program:

warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
        int* const ptr = &a;

If you want to not experience this effect, declare the pointer variable as a pointer to a constant. Example: const int* ptr=&a;

skrtbhtngr
  • 2,223
  • 23
  • 29