i) static int a, b, c;
ii) int a; int b; int c;
I am not sure as to how will the memory be allocated for these types of declaration. And if these declarations are different then how much memory is allocated for each declaration?
static int a,b,c;
will allocate three ints (probably 32bits each, or 4 bytes) in the DATA section of your program. They will always be there as long as your program runs.
int a; int b; int c;
will allocate three ints on the STACK. They will be gone when they go out of scope.
There is no difference between the size of memory for
static int a,b,c;
int a;int b;int c;
Differences occur in the lifetime, location, scope & initialization.
Lifetime: Were these were declare globally, both a,b,c sets would exist for the lifetime of the program. Were they both in a function, the static ones would exist for the program lifetime, but the other would exist only for the duration of the function. Further, should the function be called recursively or re-entrant, multiple sets of the non-static a,b,c, would exists.
Location: A common, thought not required by C, is to have a DATA section and STACK section of memory. Global variables tend to go in DATA as well as functional static ones. The non-static version of a,b,c in a function would typically go on in STACK.
Scope: Simple view: Functionally declared variables (static or not) are scoped within the function. Global variables declared static have file scope. Global variables not declared static have the scope of the entire program.
Initialization: follows along the same track as lifetime. Globally declared a,b,c, static or not, are both initialized at program start. If a,b,c are in a function, only static ones are initialized (at program start). Functional non-static a,b,c are not initialized.
Optimization may affect location, especially for the functional non-static a,b,c which could readily be saved in registers. Optimization may also determine that the variable is not used and optimizing it out, thus taking 0 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With