Memory allocation in case of static variables

I am always confused by static variables and the way memory is allocated for them.

For instance:

int a = 1; const int b = 2; static const int c = 3; int foo(int &arg){ arg++; return arg; } 

How is 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) ?

+4
source share
2 answers

I am always confused by static variables

In the global realm, static means that when linked, it will not be visible to other files.

How is memory allocated for a, b and c?

All of them will live in an executable file (for example, the __DATA segment), which will be displayed in RAM at runtime. If the compiler is good, b and c will live in a read-only data area (for example, the __TEXT segment) or even be 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 a compiler error, since const int& cannot be converted to int& .

Otherwise there is no difference. Passing by reference is equivalent to passing a pointer in the sense of the CPU. Therefore, the address of each memory is taken and foo is called.

+7
source

Memory is allocated identically for three variables. The difference is how the compiler processes them. Since b and c declared using const , the compiler will call you if you try to change their values. Since c determined by static , it will not be accessible outside the current file (using a and b you can use extern ).

The memory for all three of them will be allocated inside the executable file, which prohibits any optimizations (sometimes the compiler can eliminate the need to allocate memory for constants, filling in a constant value in all links).

Your function call will work for a , but not for b or c without an explicit cast (since your function expects a pointer to const int ). However, your compiler should understand if you try to apply a const value to a const value.

+1
source

Source: https://habr.com/ru/post/1303480/