fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <cstring>
  5.  
  6. #define LOG(index, cv, ncv) std::cout \
  7.   << std::dec << index << ".- Address = " \
  8.   << std::hex << &cv << "\tValue = " << cv << '\n' \
  9.   << std::dec << index << ".- Address = " \
  10.   << std::hex << &ncv << "\tValue = " << ncv << '\n'
  11.  
  12. int main(int argc, char **argv)
  13. {
  14. const unsigned int const_value = 0xcafe01e;
  15.  
  16. // Try with no-const reference
  17. unsigned int &no_const_ref = const_cast<unsigned int &>(const_value);
  18. no_const_ref = 0xfabada;
  19. LOG(1, const_value, no_const_ref);
  20.  
  21. // Try with no-const pointer
  22. unsigned int *no_const_ptr = const_cast<unsigned int *>(&const_value);
  23. *no_const_ptr = 0xb0bada;
  24. LOG(2, const_value, (*no_const_ptr));
  25.  
  26. // Try with c-style cast
  27. no_const_ptr = (unsigned int *)&const_value;
  28. *no_const_ptr = 0xdeda1;
  29. LOG(3, const_value, (*no_const_ptr));
  30.  
  31. // Try with memcpy
  32. unsigned int brute_force = 0xba51c;
  33. std::memcpy(no_const_ptr, &brute_force, sizeof(const_value));
  34. LOG(4, const_value, (*no_const_ptr));
  35.  
  36. // Try with union
  37. union bad_idea
  38. {
  39. const unsigned int *const_ptr;
  40. unsigned int *no_const_ptr;
  41. } u;
  42.  
  43. u.const_ptr = &const_value;
  44. *u.no_const_ptr = 0xbeb1da;
  45. LOG(5, const_value, (*u.no_const_ptr));
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
1.- Address = 0xbf8a7a7c	Value = cafe01e
1.- Address = 0xbf8a7a7c	Value = fabada
2.- Address = 0xbf8a7a7c	Value = cafe01e
2.- Address = 0xbf8a7a7c	Value = b0bada
3.- Address = 0xbf8a7a7c	Value = cafe01e
3.- Address = 0xbf8a7a7c	Value = deda1
4.- Address = 0xbf8a7a7c	Value = cafe01e
4.- Address = 0xbf8a7a7c	Value = ba51c
5.- Address = 0xbf8a7a7c	Value = cafe01e
5.- Address = 0xbf8a7a7c	Value = beb1da