Memory allocation in case of static variables

c, c++, memory, memory-management, static

Solution

I am always confused about static variables

In global scope, `static` only means it will not be visible to other files when linking.

How is the memory allocated for a,b and c?

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, `b` and `c` will live in the read-only data region (e.g. the __TEXT segment), or even eliminated in optimization.

What is the difference (in terms of memory) if I call foo(a), foo(b) and foo(c)?

`foo(b)` and `foo(c)` will be compiler error because `const int&` cannot be converted to `int&`.

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 `foo` is called.

Problem

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)`?

Original source