c++ - same address shows different values for const variable with g++ compiler -



c++ - same address shows different values for const variable with g++ compiler -

the next code shows different output gcc , g++ on using const variable i. addresses of i , value of ptr same, on accessing address printing value of i , derefrencing value of ptr got value of i 5 g++ , 10 gcc.

how g++ holds const variable in memory?

#include <stdio.h> int main() { const int =5; int *ptr =(int*)&i; *ptr = 10; printf("\n %u , %u , %d , %d \n",&i,ptr,i,*ptr); homecoming 0; }

you modifying const qualified object. not allowed in c ("undefined behavior"). can happen.

examples:

the compiler set i read-only memory. writing *ptr crash program. it set writable memory , see 10. it set writable memory replace read accesses i number 5 (you promised const, didn't you?).

i guess c compiler chose 2 while c++ compiler went 3.

c++ c

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -