This is a post about variable scopes in C. You can also learn about different storage classes like auto, extern, static and register from the Storage classes chapter of the C course.
A scope is a region of a program. Variable Scope is a region in a program where a variable is declared and used. So, we can have three types of scopes depending on the region where these are declared and used –
- Local variables are defined inside a function or a block
- Global variables are outside all functions
- Formal parameters are defined in function parameters
Local Variables
Variables that are declared inside a function or a block are called local variables and are said to have local scope. These local variables can only be used within the function or block in which these are declared. We can use (or access) a local variable only in the block or function in which it is declared. It is invalid outside it.
Local variables are created when the control reaches the block or function containg the local variables and then they get destroyed after that.
#include <stdio.h> void fun1() { /*local variable of function fun1*/ int x = 4; printf("%d\n",x); } int main() { /*local variable of function main*/ int x = 10; { /*local variable of this block*/ int x = 5; printf("%d\n",x); } printf("%d\n",x); fun1(); }
Output
5
10
4
The value of the variable ‘x’ is 5 in the block of code ({ }) defined inside the function ‘main’ and the value of this variable ‘x’ in the ‘main’ function outside this block of code ({ }) is 10. The value of this variable ‘x’ is 4 in the function ‘fun1’.
Global Variables
Variables that are defined outside of all the functions and are accessible throughout the program are global variables and are said to have global scope. Once declared, these can be accessed and modified by any function in the program. We can have the same name for a local and a global variable but the local variable gets priority inside a function.
#include <stdio.h> /*Global variable*/ int x = 10; void fun1() { /*local variable of same name*/ int x = 5; printf("%d\n",x); } int main() { printf("%d\n",x); fun1(); }
Output
10
5
You can see that the value of the local variable ‘x’ was given priority inside the function ‘fun1’ over the global variable have the same name ‘x’.
Formal Parameters
Formal Parameters are the parameters which are used inside the body of a function. Formal parameters are treated as local variables in that function and get a priority over the global variables.
#include <stdio.h> /*Global variable*/ int x = 10; void fun1(int x) { /*x is a formal parameter*/ printf("%d\n",x); } int main() { fun1(5); }
Output
5