hi,
I had a basic question about memory storage. I have seen many threads and was somewhat confused.
where would the following be stored
1) Automatic variables ( local variables within function, and function parameters)
2) Register variables
3) static variables with no linkage( within function or block)
4) static variable with external linkage ( global variable available in multiple files)
5) static variable with internal linkage( global variable for the current file)
6)volatile variable
7) variables with "new" (dynamic memory)
Also, consider the following code taken from C++Primer.
Code:
#include <iostream>
using namespace std;
double warming = 0.3; // external variable
void update(double dt);
void local();
int main()
{
cout << “Global warming is “ << warming << “ degrees.\n”;
update(0.1); // call function to change warming
cout << “Global warming is “ << warming << “ degrees.\n”;
local(); // call function with local warming
cout << “Global warming is “ << warming << “ degrees.\n”;
return 0;
}
void update(double dt) // modifies global variable
{
extern double warming; // optional redeclaration
warming += dt;
cout << “Updating global warming to “ << warming;
cout << “ degrees.\n”;
}
void local() // uses local variable
{
double warming = 0.8; // new variable hides external one
cout << “Local warming = “ << warming << “ degrees.\n”;
// Access global variable with the // scope resolution operator
cout << “But global warming = “ << ::warming;
cout << “ degrees.\n”;
}
the program results is
Code:
- Global warming is 0.3 degrees.
- Updating global warming to 0.4 degrees.
- Global warming is 0.4 degrees.
- Local warming = 0.8 degrees.
- But global warming = 0.4 degrees.
- Global warming is 0.4 degrees.
My question is following
a) if the statement
Code:
extern double warming;
was not used, still variable "warming" inside the function update(dt) would be treated as global and its value updated to 0.4?
b) when in function local(), variable "warming" is created again as local variable, what happens in memory? does the compiler create another variable with vale 0.8 with different name and "cout" prints it rather than the variable warming or does the compiler create 2 variables in memory with same name and know which one to print?
Thanks
sedy