-1

As far as I know, you can change the value of a const if you dereference a pointer to it (int *prt). However, I'd expect this to return x = 20, not x = 10.

#include <stdio.h>

int main() {
    const int x = 10;
  
    int* y = &x;
    *y = 20;
  
    printf("x = %i\n", x);
  
    return 0;
}

The compilers (both gcc and clang) throw a warning, but let me compile (as expected). I did my research before posting, but everything suggests I should be able to change x. The code looks almost exactly like this which I tried too, and I couldn't manage to change var's value.

Also read this, this and this which further prove I should be getting the expected output x = 20 and not x = 10.

Running macOS on a 2020 M1 MacBook Air.

  • Disable optimization and pray. [https://wandbox.org/permlink/9kkxV7DnRu2LsGdF](https://wandbox.org/permlink/9kkxV7DnRu2LsGdF) – MikeCAT Jun 04 '22 at 04:43
  • It's undefined behavior. – Retired Ninja Jun 04 '22 at 04:56
  • 1
    "everything suggests I **should** be able to change `x`" Everything doesn't include the C specification, which says *"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."* – user3386109 Jun 04 '22 at 04:58
  • Since you have declared it a `const` the compiler will probably optimize the memory accesses, especially when you use the optimization switches(`-O`). In general, is **UB** , so there is no *expected output* that you should be getting. [Proof](https://godbolt.org/z/5KTKno3G5). – alex01011 Jun 04 '22 at 04:58
  • 4
    Also, there is no logic behind declaring a variable `const` and then attempting to modify it. – alex01011 Jun 04 '22 at 05:00

0 Answers0