Scope rules in C programming refers to the accessibility or validity of a variable within a certain region of a program. Otherwise, you can say in general as it is a lifetime of a variable at a given point in a program.


Types of scope in C

  • Local scope
  • Global scope
  • File scope

Local Scope

The variable which is declared inside any function is termed a local variable and is limited to that function. Thus it is accessible within that function. You can say within the opening and closing curly braces({}) of a function. It is known to be local scope or block scope.

Example

#include<stdio.h>
int main()
{
  int a=10;
  printf("Value of a is %d \n",a);
  return 0;
}

Code explanation

In the above program “a” is a variable that is declared within the main function. Thus it becomes local to the main function. Outside the main function,i.e. outside the opening and closing curly braces of the main function, it does not have an existence.


Global Scope

The variable which is declared in the global declaration section is known as the global variable. It is declared before the main function. Thus its scope is the global scope. i.e. it can be accessed anywhere in the program. The global variable if not initialized then takes the value “0”(If it is a pointer then it is initialized to null).

Example

#include<stdio.h>
int a=10;
int main()
{
 int b=20;
 printf("Value of a and b are %d and %d \n",a,b);
 return 0;
}

Code explanation

In the above program, “a” is declared outside the main function, thus it becomes global variable. It can be accessed anywhere in the program. Here “a” is accessed within the main function and it is showing the result to be 10 Whereas variable “b” is local variable and its scope is limited to the main function.


File Scope

If the variable is declared outside of all functions, then it is accessible in that file hence File Scope. i.e. it is accessible from the beginning of a file to the end of a file. To declare a variable to have file scope, you need to add a static keyword at its beginning during declaration. For example, static int a=”10″;.


People also ask for

What is scope in programming?

Scope refers to the accessibility or validity of a variable within a certain region of a program. Otherwise what you can say in general as it is a lifetime of a variable at a given point in a program.