Strange c++ pointer behavior. | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

Strange c++ pointer behavior.

Can anyone explain me what is happening in this code? https://code.sololearn.com/cV9D58KF6g7Z/?ref=app

5th Jan 2019, 1:28 PM
Ali Hoori
Ali Hoori - avatar
3 Respuestas
+ 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: https://stackoverflow.com/questions/15576000/in-c-can-a-const-variable-be-modified-via-a-pointer [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!): https://godbolt.org/z/DAcdgx
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
program - avatar
0
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