What is Program Scope in C?

Share

In the C language, the variable’s scope refers to the part of the program where we reference it. The two types of variables in C are:

  1. Local variables: These are defined within a function body. They are not accessible outside the function.

  2. Global variables. They are defined outside the function body. Thus, they are accessible to the entire program.

Program scope

Global variables declared outside the function bodies have a program scope. The availability of global variables stays for the entire program after its declaration. Moreover, global variables are initialized automatically by the compiler.

A global variable declared with the static keyword has a File Scope. To find out more about this, click here.

Example

The following example shows two global variables, a and b. As seen in the code below, these variables are accessible by both the test function and the main function:

#include <stdio.h>
//Declare Global Variables
int a = 8;
float b = 7.5;
int test(){
b = b + a;
return b;
}
int main(){
//Access a
printf ("The value of a is: %d\n", a);
//Access b
printf ("The value of b is: %f\n", b);
return 0;
}
Copyright ©2024 Educative, Inc. All rights reserved