12
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?

Jens Gustedt
  • 74,635
  • 5
  • 99
  • 170
xiaokaoy
  • 1,568
  • 3
  • 13
  • 26

5 Answers5

15

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.

11

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).

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
6

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.

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
6

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)

phoxis
  • 56,382
  • 14
  • 80
  • 112
3

When you do *p=20, you are trying to change the value of a constant, which is not allowed.

Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197
Aakash Anuj
  • 3,633
  • 7
  • 32
  • 45