I am always confused about static variables, and the way memory allocation happens for them.
For example:
int a = 1;
const int b = 2;
static const int c = 3;
int foo(int &arg){
arg++;
return arg;
}
How is the memory allocated for a,b and c?
What is the difference (in terms of memory) if I call foo(a), foo(b) and foo(c)?
In global scope,
staticonly means it will not be visible to other files when linking.All of them will live in the executable file (e.g. the __DATA segment) which will be mapped into the RAM on execution. If the compiler is good,
bandcwill live in the read-only data region (e.g. the __TEXT segment), or even eliminated in optimization.foo(b)andfoo(c)will be compiler error becauseconst int&cannot be converted toint&.Otherwise no difference. Pass by reference is equivalent to pass by pointer in the CPU’s sense. So the address of each memory is taken, and
foois called.