tabs_over_spaces
tabs_over_spaces

Reputation: 362

Changing value of const by pointer

This answer at this question explains how changing a constant variable via dereferencing a pointer to it's address works (apparently by creating a new variable).

const int i = 10;
*(int *)&i = 5;

std::cout << &i << "\t" << i << "\n";                   // 0x7fff6b325244   10

std::cout << &*(int *)&i << "\t" << *(int *)&i << "\n"; // 0x7fff6b325244   5

With &*(int *)&i I was trying to get the address of the new variable that the previous answer was talking about. How do I find where this new variable is stored?

*(int *)&i is showing a different value, so there has to be a new variable.

Compiled on g++ 5.4.0, Ubuntu 16.04

Upvotes: 0

Views: 118

Answers (2)

Miles Budnek
Miles Budnek

Reputation: 30494

The behavior when changing the value of a variable declared const is undefined. The compiler doesn't have to do anything that makes sense.

In this case, the compiler doesn't bother to look into memory when printing the const value i, since it knows that value couldn't have possibly been altered by any conforming code. When you print i, it generates this assembly:

mov     esi, 10
mov     rdi, rax
call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)

Notice that it just hard-codes 10 in that call.

Upvotes: 6

Zulan
Zulan

Reputation: 22670

As the original answer points out correctly:

It's "undefined behaviour", meaning that based on the standard you can't predict what will happen when you try this. It may do different things depending on the particular machine, compiler, and state of the program.

Anything is fair game, including what you observe, which is probably just the result of a compiler optimization. You shouldn't spend to much time trying to interpret undefined behavior.

Edit: To be more clear regarding the recommendation: DO NOT DO THAT.

Upvotes: 3

Related Questions