1

I read that constant values cant be changed but in this code below the value of i is getting changed through the use of a pointer. May I know how?

#include <stdio.h>

int main()
{
    const int i = 10;
    int *ptr = &i;
    *ptr = 20;
    printf("%d\n", i);
    return 0;
}

The output of this code is 20 with a compiler warning.

Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39

1 Answers1

3

The behaviour of your code is undefined - the language does not define the behaviour of modifying an object originally declared as const via a pointer that's had const stripped from it.

On some compilers with optimisations turned on, getting 10 as the output is reasonable.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483