Scope
Local Variable in Function
#include <stdio.h>

void doubleNum(int a) // a is a local variable of the function
{
	a = 2*a;

	printf("a in doubleNum function: %d, %p\n", a, &a);
}
 
int main()
{
	int a = 10;

	printf("a in main function: %d, %p\n", a, &a);

	doubleNum(a);

	printf("a in main function: %d, %p\n", a, &a);
}
		

Local Variable in Block
#include <stdio.h>
 
int main()
{
	int a = 10;

	printf("a in function: %d, %p\n", a, &a);
 
	{
		int a = 100; //screen the a in main function
		printf("a in block: %d, %p\n", a, &a);
	}

	printf("a in function: %d, %p\n", a, &a);
}
		
#include <stdio.h>
 
int main()
{
	int a = 10;

	printf("a in function: %d, %p\n", a, &a);
 
	for(int a = 0; a < 5; a++) // screen the a in  main function
	{
		printf("a in block: %d, %p\n", a, &a);
	}

	printf("a in function: %d, %p\n", a, &a);
}
		
Global Variable and Local Variable
#include <stdio.h>
 
int a = 10; // global variable
 
void display()
{
	printf("Global a in display: %d, %p\n", a, &a);

	int a = 1000; // screen global a

	printf("Local a in display: %d, %p\n", a, &a);
}
 
int main()
{
	printf("Global a in main: %d, %p\n", a, &a);

	int a = 100; // screen global a

	printf("Local a in main: %d, %p\n", a, &a);

	display();

	return 0;
}
		
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>
    
    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
    }
    		
    // main.c
    #include <stdio.h>
    
    extern int a;
    
    int main()
    {
    	printf("a: %d\n", a);
    }
    		
    // util.c
    int a = 10;
    		
    Reference