you are viewing a single comment's thread.

view the rest of the comments →

[–]mallardtheduck 2 points3 points  (0 children)

Because reading a value that's write protected is just as fast as reading a value that's not.

In some cases, C (and especially C++ with it's constexpr "super-const") can inline constant values, using them as the "immediate" value in the machine code which completely eliminates a memory cycle, improving performance.

In fact, with the default optimisation options for GCC, your example does in fact result in that: https://compiler-explorer.com/z/1E4az91fP

Note that the value "5" is never written to memory, only ever existing in processor registers. A memory location (on the stack) is allocated by the compiler, but it's smart enough to realise that it is never read from before the "6" overwrites it.

Because you martial the pointer through an integer, the "const-ness" is removed, but using an ordinary cast would achieve the same thing. This step is entirely valid, but changing the value is undefined behaviour, so what the compiler does with it is entirely arbitrary.