I am learning about the way memory is modeled in C. I know that there are basically four different parts. Static memory, stack, heap and program memory. I know that when something is declared static, its lifetime (and not necessarily its visibility) is the entire program. So let's say I have written something like this:
#include <stdio.h>
void add();
main(){
int i;
for (i=0; i<6;++i){
add();
}
return 0;
}
void add(){
static int x=5;
x++;
printf("The value of x is %d\n", x);
}
The program keeps track of the value of x
till the last execution. If I write the program like this, I get pretty much the same result:
#include <stdio.h>
int x=5;
add(int *num){
(*num)++;
printf("The value of x is %d\n", *num);
}
main(){
int i;
for (i=0; i<6;++i){
add(&x);
}
return 0;
}
I didn't use the static
keyword, but because of its cope, the program keeps track of its value in successive executions of the add()
function. I'd like to know if in both of these cases, the way x
is handled in memory is the same. Is the second x
also treated as static?