0

I came across this piece of code in which I was able to modify the value of an const int variable! But is this a bug or a hack? Please clarify me:

#include<stdio.h>
int main(void)
{
    const int a = 10;
    int* ptr = &a;

    printf("\n value at ptr is  : [%d]\n",*ptr);
    printf("\n Address pointed by ptr  : [%p]\n",(unsigned int*)ptr);

    *ptr = 11;
    printf("\n value at ptr is  : [%d]\n",*ptr);
    printf("\n %d",a);

    return 0;
}

Output:

value at ptr is : [10]

Address pointed by ptr : [0xbf9e614c]

value at ptr is : [11]

11

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
highlander141
  • 1,683
  • 3
  • 23
  • 48

1 Answers1

0

No, this is undefined behaviour.

If you attempt to modify a const-qualified variable through a non-const qualifier pointer, it invokes UB.

Quoting C11, chapter ยง6.7.3, Type qualifiers

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261