1

I cant understand why this is working.

#include<stdio.h>

void main(){
  const int x = 100;
  printf("x = %d \n",x);
  scanf("%d",&x); //working fine
  printf("x = %d \n",x); //prints the new value
}  
vrsm
  • 19
  • 5

3 Answers3

4

It's not working fine, modifying const variables are undefined behavior. Anything could happen.

Using -Wall with GCC, you will see:

warning: writing into constant object (arg 2)

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

It's UB generally.
May be you see result of a casting in your case.
For example:

void main(void)
{
    int const x = 100;
    int *x2 = &x;
    *x2 = 2; 
}   

is working on my machine, but

void main(void)
{
    int const x = 100;
    x = 2; 
}  

isn't (compilation error).
Anyway, it is better not to change the const variables.

someuser
  • 189
  • 1
  • 11
2

It is possible to change it but the behavior is undefined, as its mentioned in the standard!

Its in c11 under 6.7.3

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. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

dhein
  • 6,431
  • 4
  • 42
  • 74