2. Scope of a variable
A scope in any programming is a region of
the program where a defined variable can
have its existence and beyond that variable
it can’t be accessed.
Three places to declare variable:
1. inside a function or block (local
variables)
2. outside of all the functions (global
variables)
3. in the definition of function
parameters (formal parameters)
3. Local Variables
• Variables that are declared inside a function or block
are called local variables.
• They can be used only by statements that are inside
that function or block of code.
• Local variables are not known to functions outside
their own.
12. Global Variables
• Global variables are defined outside a function,
usually on top of the program.
• Global variables hold their values throughout the
lifetime of your program.
• A global variable can be accessed by any function i.e.
a global variable is available for use throughout the
entire program after its declaration.
16. Sample Program
#include<stdio.h>
int g=0; ///global variable
int main()
{
printf("%dn",g); ///0
int i;
for(i=1;i<=5;i++){
int j=i;
printf("%dn",j);
g=g+j;
}
return 0;
}
17. Sample Program
#include<stdio.h>
int g=0; ///global variable
int main()
{
printf("%dn",g); ///0
int i;
for(i=1;i<=5;i++){
int j=i;
printf("%dn",j);
g=g+j;
}
printf("%dn",j); ///error
printf("%d %dn",i,g); ///6 15
return 0;
}
18. Special Case
• A program can have same name for variables within
different scope.
• A program can have same name for local and global
variables but the value of local variable inside a
function will take preference.