Strange c++ pointer behavior. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Strange c++ pointer behavior.

Can anyone explain me what is happening in this code?

5th Jan 2019, 1:28 PM
Ali Hoori
Ali Hoori - avatar
3 Answers
+ 2
The code is mixing up "compile time' and "runtime" assumptions. When your code is compiled, the compiler (in this case!) is tracking constants (err, ro-values) and substituting their values into the final executable. What you're doing is undefined/compiler-specific/should throw a warning / discard 'const', etc See the explanations here: [inside the compiler] Here's the assembly for your code. It has never run, so you are seeing "compile-time" decisions. You can see that the compiler believes 'a' is supposed to have its original value so it substitutes it into the assembly (no runtime memory is involved!):
5th Jan 2019, 4:43 PM
Kirk Schafer
Kirk Schafer - avatar
+ 14
// Hi Ali Hoo, In the line 6, you use "const" to create a variable. But if you use const, the value cannot be modified. Correction : delete "const" in the line 6
5th Jan 2019, 1:33 PM
program - avatar
Thank you. But my compiler (vs 2017) didn't show any warning. My executable work fine and shows the same output. I changed const with constexpr but I got the same answer.
5th Jan 2019, 6:05 PM
Ali Hoori
Ali Hoori - avatar