#include <iostream> void f(const int* var) { *var = 42; } int main() { int* ptr = new int(78); f(ptr); std::cout << *ptr << std::endl; return 0; }
[scott_s@local Code] g++ const.cpp const.cpp: In function ‘void f(const int*)’: const.cpp:5: error: assignment of read-only location
#include <iostream> void f(const int* var) { int* sneaky = const_cast<int*>(var); *sneaky = 42; } int main() { int* ptr = new int(78); f(ptr); std::cout << *ptr << std::endl; return 0; }
[scott_s@local Code] g++ const.cpp [scott_s@local Code] ./a.out 42