views:

364

answers:

2

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

+7  A: 

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.

KennyTM
+1  A: 

Memory is allocated identically for your three variables. The difference is in how the compiler treats them. Since b and c are declared with const, the compiler will gripe at you if you attempt to modify their values. Since c is defined static, it will not be accessible outside of the current file (both a and b can be accessed using extern).

The memory for all three of these will be allocated inside the executable file barring any optimizations (sometimes the compiler can eliminate the need to allocate memory for constants by filling in the constant's value everywhere it is referenced).

Your function call will work for a but not for b or c without explicit casting (since your function is expecting a pointer to a non-const int). However, your compiler should gripe at you if you attempt to cast a const value to a non-const value.

bta