0

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?

Morteza R
  • 2,229
  • 4
  • 20
  • 31
  • possible duplicate of [What does "static" mean in a C program?](http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program) – ThisaruG Feb 24 '15 at 02:56
  • Yes, it is. The only difference between global variables and static local variables is scope. –  Feb 24 '15 at 02:57
  • Then why would someone still write `static int x =5` outside of the main function? Wouldn't it be superfluous if its already static? I am sure I have seen something like that. – Morteza R Feb 24 '15 at 03:00
  • 2
    You have to consider a program large enough that the source code is in multiple files. In that case, a `static` variable has file scope, i.e. is not visible to code in other files. If all of the code is in *one* file, then there is no difference between a global variable (not declared `static`), and a file-scope variable (declared as `static` outside of any function). – user3386109 Feb 24 '15 at 03:03
  • @user3386109 Thanks. Enlightening comment. – Morteza R Feb 24 '15 at 03:10

1 Answers1

3

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.

Kavindu Dodanduwa
  • 12,193
  • 3
  • 33
  • 46