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
  • 76,821
  • 6
  • 102
  • 177
xiaokaoy
  • 1,608
  • 3
  • 15
  • 27
  • 3
    I gave your question a title that summarizes its contents. Don't use such generic titles as you did, they don't help anybody. – Jens Gustedt Aug 02 '13 at 06:46
  • 2
    [C/C++ changing the value of a const](http://stackoverflow.com/questions/583076/c-c-changing-the-value-of-a-const) – Grijesh Chauhan Aug 02 '13 at 07:12
  • 2
    [Can we modify the value of a const variable?](http://stackoverflow.com/questions/12245333/can-we-modify-the-value-of-a-const-variable) – Grijesh Chauhan Aug 02 '13 at 07:13

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
  • 476,176
  • 80
  • 629
  • 1,111
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
  • 119,891
  • 44
  • 235
  • 294
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
  • 60,131
  • 14
  • 81
  • 117
3

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

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Aakash Anuj
  • 3,773
  • 7
  • 35
  • 47