Q:

Declaring a global and a static variable

I was studying about static variable and i came across this code on wikipedia . The static int x stores it value throughout the programme. And even when we declare it globally it will store the previous values. Does this mean static and global variables are treated as same .And if not ,how does the both work ?
#include <stdio.h>

 void func() {
       static int x=0;
        // x is initialized only once across three calls of func()
        printf("%d\n", x); // outputs the value of x
        x = x + 1;
}

 int main(int argc, char *argv[]) {
        func(); // prints 0
        func(); // prints 1
        func(); // prints 2
        return 0;
}

A:

The specifier static has a slightly different meaning depending where you use it. You have 3 options to declare a variable whose value you want to be preserved throughout the lifetime of the program:
1) When declaring a variable as static within a function (that is a local variable) means that its value will be preserved between function calls throughout the lifetime of the program. If you initialize the variable to a value, this is the starting value of that variable on the first function call; all subsequent function calls will have the value of the variable preserved instead of re-initialized.
2) When declaring a global variable (without the static specifier), its value is preserved throughout the lifetime of the program as if it were a local static variable, but the difference is that a global variable is visible (to be read and written to) by any function of any file of the program.
3) When declaring a global static variable, its value is again preserved throughout the lifetime of the program, but in contrast to plain global variables, it can only be accessed by other functions within the same file.
In conclusion, all these three types of variables have their value preserved; the difference lies in their scope, meaning which functions have access to this variable.
All 3 variables of the following code preserve their value thoughout the life of the program.
int x = 100;         // visible to any function within any .c file of this program
static int y = 5000;  // visible from any function within this .c
int func (int i)
{
  static int z = 0;      // invisible to all other functions
  x += i;
  y += i;
  z += i;
  return z;
}

A thorough explanation can be found here.

