0
#include <stdio.h>

int main(){
    const int a = 10;
    *(int*)(&a) = 9; // modify a
    printf("%d", a);
    return 0;
}
  • When I run this code on Xcode, the output is 10 (not changed)
  • When I run this code on Visual Studio Community, the output is 9 (changed)

Why?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
dispute
  • 1,424
  • 13
  • 17

3 Answers3

8

This program would compile but exhibits undefined behavior and may output 9 or 10 or something else or may crash who knows.

When you say a is const, you promise that you won't try change the value of a directly or indirectly and compiler may make certain assumptions. If you break the promise unexpected things may happen.

Gyapti Jain
  • 4,056
  • 20
  • 40
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
5

Q: why?

Ans: undefined behaviour.

To explain, if you try to modify a const variable value by accessing is through some non-const pointer, it invokes undefined behaviour.

As per C11 standard, chapter 6.7.3, paragraph 6.

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.

Note: The recommended signature of main() is int main(void).

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

const keyword is used not to change the value of variable. If its done forcefully results may be unexpected

Pawan
  • 167
  • 12