+ 10
Why this code every time gives different output when you run it multiple times?
The shared link and code is from "pointers" tutorials. It displays int score = 5; and that which denotes its memory location. Does that memory location always changes || it repeats || it stay same? Help me understand it better. Thanks in advance! Pointers description: Every variable is a memory location, which has its address defined. That address can be accessed using the ampersand (&) operator (also called the address-of operator), which denotes an address in memory. //This outputs the memory address, which stores the variable score. https://www.sololearn.com/learning/1051/1630/2858/1 #include <iostream> using namespace std; int main() { int score = 5; cout << &score << endl; return 0; }
4 Answers
+ 11
Whenever you declare a variable in c++ (or any other programming language) and compile your code, the compiler automatically allocates each variable to a memory location.
These memory locations may change if you rerun the program ( they are stored in RAM, and are deleted when the program closes), but they stay the same throughout the same execution.
So for example:
If you declare int a=3;
And then cout &a multiple times in the same program, it will always print out the same value ( the current variable location in ram).
But once you exit your program and restart, the variable is deleted, and will be declared again in a different place when you rerun your program.
+ 7
Thanks Mohamad Kamar !
However, my question still remains the same. It is because, I reran the code without exiting.
+ 6
Thanks for the explanation CarrieForle !
That make sense now. It was completely out of my mind on how code exit automatically.
+ 1
Shivani 📚 [Less Active] once the code execution is done. The code exit automatically. That is, when the main() gets to the return statement.