Morteza R
Morteza R

Reputation: 2319

How differently are these two variables handled in memory

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?

Upvotes: 0

Views: 66

Answers (1)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13059

Is the second x also treated as static?

No Second x is not treated as Static. You can still make second variable Static which would result in a different result. If second x is declared as static "scope will be limited to file" but in your case it is NOT limited to file.

And yes in both cases x lives the lifetime of the program but note the use of braces which limit the scope,

In second case x is only limited to scope of the function add()

void add(){  // <= From here

    static int x=5;
    x++;
    printf("The value of x is %d\n", x); 

} // <= to here

And for second case x is global and accessible from other files too.

Upvotes: 3

Related Questions