heading


Variable Scopes Local and Global

In programming, a scope is an area of the program where a declared variable can exist but cannot be accessible beyond that variable. In the C programming language, variables can be defined in three places:

Local variables are variables that exist within a function or a block.

Global variables are variables that exist outside of all functions.

Formal parameters are used in the definition of function parameters.

Let's define local and global variables, as well as formal parameters.

Local Variables

Local variables are defined within a function or block, and they can only be utilized by statements that are included within that function or code block. Local variables aren't known to have any effect outside of their scope. The following example demonstrates the usage of local variables. The variables a, b, and c are all local to the function main().

#include<stdio.h> #include<conio.h> void main() { int a,b,c; /* local variable declaration */ /* actual initialization */ a=10; b=20; c=a+b; printf("a=%d,b=%d and c=%d",a,b,c); getch(); }

output:

a=10,b=20 and c=30

Global Variables

Global variables are declared outside of a function, generally at the beginning of a program. Global variables maintain their values throughout the life of your program and may be accessed from any of the program's functions.
Any function has access to a global variable. Once a global variable is declared, it is available for usage throughout the whole program. The following program demonstrates the use of global variables in a program.

#include<stdio.h> #include<conio.h> int c; void main() { int a,b; a=10; b=20; c=a+b; printf("a=%d,b=%d and c=%d",a,b,c); getch(); }

output:

a=10,b=20 and c=30

Local and global variables in a program can have the same name, but the value of a local variable inside a function takes precedence. Here's an illustration:

#include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; }