C/C++ changing the value of a const

后端 未结 18 1785
醉梦人生
醉梦人生 2020-11-28 07:28

I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to repli

18条回答
  •  执念已碎
    2020-11-28 07:38

    Some of these answers point out that the compiler can optimize away the variable 'a' since it is declared const. If you really want to be able to change the value of a then you need to mark it as volatile

      const volatile int a = 3; // I promise i won't change a
      int *ptr = (int *)&a;
      (*ptr) = 5; // I'm a liar, a is now 5
    

    Of course, declaring something as const volatile should really illustrate just how silly this is.

提交回复
热议问题