0

I read that in link, that assigning address of const int * to int * is illegal for C++ and throws compiler error. I tried assigning the const int * to int * by explicit cast and tried changing the value. I couldn't understand the program behavior. I was wondering if it is undefined behavior or there is some reasoning behind it.

#include <stdio.h>

int main()
{
    int const i = 20;
    int * ptr;

    ptr = (int *)&i;

    *ptr = 500;

    printf("%d %d %p %p\n", *ptr, i, ptr, &i);

    return 0;
}

The output was

500 20 0x7ffe16ea5134 0x7ffe16ea5134
Tushar Goyal
  • 212
  • 3
  • 15
  • 7
    It is Undefined Behaviour. – Edgar Rokjān Jan 06 '17 at 19:06
  • 5
    Modifying a `const` object is always UB – NathanOliver Jan 06 '17 at 19:07
  • See: [Can we change the value of an object defined with const through pointers?](http://stackoverflow.com/q/3801557/1275169). – P.P Jan 06 '17 at 19:09
  • 1
    Cast away the `const` to defeat the compiler warning, and you are off on your own. – Weather Vane Jan 06 '17 at 19:09
  • Also, a const object cannot be modified. so its undefined behavior. – Abc Jan 06 '17 at 19:09
  • Casting `const int *` to `int *` like that will compile, but it doesn't mean that it is allowed in this case. Many things that are not allowed will compile. See [undefined behavior](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). – François Andrieux Jan 06 '17 at 19:09
  • @FrançoisAndrieux Casting away the constness is perfectly acceptable... but only in a few scenarios (which actually includes some where you want to modify the value!) – AndyG Jan 06 '17 at 19:11
  • @AndyG specifically, it's allowed when the original object wasn't `const` to begin with. That's why `const_cast` exists. – Mark Ransom Jan 06 '17 at 19:13
  • 1
    As far as the output in this example, it's indeed UB since it makes no sense. If you're wondering what the compiler did to get this specific result, it probably optimized the `i` in the `printf` call to a literal since it knew the value couldn't be changed. – Mark Ransom Jan 06 '17 at 19:17
  • Thanks for your explanation. I think it makes sense that since compiler could see that that i is const and hence instead of using reference to variable it used the value directly as immediate in assembly. – Tushar Goyal Jan 06 '17 at 19:33

0 Answers0