Scope
Global Variable and Local Variable
#include <stdio.h>

int a = 10; // global variable

int doubleNum(int a) // n is a local variable of the function
{
	return 2*a;
}

int main()
{
	int b = 100; // local variable
	printf("a: %d, b: %d\n", a, b); // 10, 100

	int a = 1000; // local variable screen global variable
	printf("a: %d, b: %d\n", a, b); // 1000, 100

	printf("a in function: %d\n", doubleNum(1)); // 2

	{
		int c = 5;
		printf("a: %d\n", a); // 1000
		printf("c: %d\n", c); // 5
	}

	//printf("c: %d\n", c); // error
}
		
Storage classes
  • auto, this is the default storage class for all the variables declared inside a function or a block, auto variables can be only accessed within the block/function they have been declared
  • register, this storage class declares register variables which have the same functionality as that of the auto variables, but store these variables in the register of the microprocessor if a free register is available
  • static, keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope
  • extern, simply tells us that the variable is defined elsewhere and not within the same block where it is used
  • #include <stdio.h&gr;
    
    void f()
    {
    	static int c = 0; // static variable
    	int d = 0; // auto variable
    	c++;
    	d++;
    
    	printf("c: %d\n", c);
    	printf("d: %d\n", d);
    }
    
    int main()
    {
    	auto int a = 10; // auto
    
    	printf("a: %d\n", a); // 10
    
    	register int b = 100; // register
    
    	printf("b: %d\n", b); // 100
    
    	f(); // 1, 1
    
    	f(); // 2, 1
    }
    		
    // s3.c
    #include <stdio.h>
    
    extern int a;
    
    int main()
    {
    	printf("a: %d\n", a);
    }
    		
    // util.c
    int a = 10;
    		
    Reference