2

Why this works? a and b has same ptr address but value differs?

#include <stdio.h>

int main()
{
    const int a = 10;
    int *b = (int *) &a;
    *b = 20; 

    printf("addr=%d val=%d\n",&a,a); //addr=455682860 val=10
    printf("addr=%d val=%d\n",b,*b); //addr=455682860 val=20

    return 0;
}
  • this is a result of lying to the compiler. The duplicate link is for C++ but the answer is the same. let's keep this duplicate for the c tag. – Jean-François Fabre Sep 08 '18 at 14:37
  • pls try it again, it should show the same values. btw, for memory address one should use %p in the format string – Gergely Nyiri Sep 08 '18 at 14:40
  • @GergelyNyiri "try it again"? well, it will yield the same results. Read the dupe link – Jean-François Fabre Sep 08 '18 at 14:40
  • 2
    You break the contract with the compiler. You say that the object is not changable but you try to find the way how to modify it. It is an Undefined Behavior - you got compiler warnings. In many implementations the object will placed in the Read Only memory and attempt to modify it will be unsuccessful (for example uC FLASH memory) or/and protected against the writes causing the hardware exceptions (SIGFAULTs and similar) – 0___________ Sep 08 '18 at 14:41
  • Thank you @Jean-FrançoisFabre for the link. Indeed - "The compiler is allowed to optimize any mention of a const to be as though you had written its compile-time value in there." When I change "const int a = 10;" to "volatile const int a = 10;" everything start work fine. – Anton Miroshnichenko Sep 09 '18 at 17:27

0 Answers0