const int a = 10
int *p = (int*) &a;
*p = 20;
printf("a = %d", a);
Is it possible to output either 10 or 20, depending on the compiler?
const int a = 10
int *p = (int*) &a;
*p = 20;
printf("a = %d", a);
Is it possible to output either 10 or 20, depending on the compiler?
Is it possible to output either 10 or 20, depending on the compiler?
Yes, or even nasal demons can appear. The behavior of this program is undefined, the code is ill-formed, because modifying a const
object is a constraint violation.
As it's written, your code has undefined behavior, so yes, you could get 10 or 20 or anything else (e.g., an access violation).
It's undefined behavior:
C11 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. 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.
Yes it is undefined behaviour, and I think this is where is tells about it.
C99 Section 6.7.3 Paragraph 5
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.115)
When you do *p=20
, you are trying to change the value of a constant, which is not allowed.