What are the Variables Scope Rules in C Programming

What are the Variables Scope Rules in C Programming

Scope rules in C or variable scope means where the variable can be directly accessed after its declaration.
In the C programming language, the scope of a variable can be stated in three places:

ScopeDescription
Local VariableInside a function or block
Global variableOutside of all function(can be accessed from anywhere)
Formal ParametersIn the function parameters

You must test the C Language code provided in this lesson in your code editor to validate it. However, if you prefer to execute this code online, we also provide a free C Online Compiler for testing your C Language code.

The scope of an identifier in C programming is the area of the program where the identifier can be directly accessed.

Variables and Variable Naming Rules...
Variables and Variable Naming Rules in Python (Video 08)

The rule of the scope of a variable in C tells what the scope of that variable is. For instance, local scope, global scope, or just formal parameters.

If a variable’s scope is local, it can only be accessed locally. For example, if a variable is declared within a function, its scope is limited to that function.

It signifies that there are no variables with that name outside of that function until a new variable with the same name is defined.

And if a variable’s scope is global, it can be accessed from anywhere in the program or from anywhere in the world. In the case of formal parameters, it is similar to a local variable that can only be known by that function.

So, if you want to utilize the same variable from one function to the next and from one location to the next, use the global variable, which means define the variable globally.

And if you want to use a variable locally, it means you only want to use the variable for local activity and then destroy it, so use the local variable. Let’s go over the C scope rules one by one, from local variables to formal parameters.

Local Variables

Local Variables is Variables declared within a block or function. Because the variable is declared and utilized locally, it is referred to as a local variable.

Local variables can only be utilized within the block or function where they are declared. It becomes unknown outside of that function or block and is deleted upon quitting that function or block.

So, if you only want to utilize a variable for a short period of time, for a specific purpose, or for a certain location, function, or block, simply use the local variable.

If you enter the function or block where the variable is defined, the variable will work and be removed immediately when you exit the function or block.

Example of Local Variables in C

/* C Scope Rules - Local Variable Example */
#include<stdio.h>
int main()
{
   int a;
   
   a = 10;
   printf("Outer (before) a : %d\n", a);
   if(a==10)
   {
      int a;   // this a hides the outer a
      a = 9;
      printf("Inner a : %d\n", a);
   }
   printf("Outer (after) a : %d\n", a);
   return 0;
}

Output of the above example:

Outer (before) x : 10
Inner x : 9
Outer (after) x : 10

Explanation

Here, the first value of an x is 10, which is outside the if block, and after declaring it, we initialized the value of an x is 9.

As a result, when we exit the if block, the value of an is deleted and the outer value, 10, is retained, as seen in the output figure. Keep this change in mind at all times.

Local variables can be utilized by local statements only where they are defined, i.e. the variable’s scope is local, which implies the variable cannot be accessed from outside the blocks where it is declared.

Variables become unknown outside the block since their scope is local only. This is due to the fact that a local variable is only created upon entry to that block and removed automatically on exit.

The scope of the global variable is throughout the program since it is created when the program begins execution and destroyed when the program terminates execution.

You can try to test here the example above!

Another Example of Local Variables in C

#include <stdio.h>
   
    int main()
    {
      /* Declaration of local variable  */
  int x;
  
 
  /* initialization */
  x = 7;
  
 
  printf ("value of x = %d\n", x);
      return 0;
    }

Output of the above example

value of x = 7

You can try to test here the example above!

Global Variables in C

Global Variables in C are variables defined outside of a function, usually at the start of the program, i.e. above the main() function. Throughout the program, a global variable is known.

The values of global variables are retained throughout the program. As a result, the Global variables are available throughout the program, from outside to inside the functions or blocks. In brief, global variables can be accessed from anywhere in the application.

Important: If the names of the global variable and the local variable are identical, the local variable takes precedence. This signifies that the first local variable will be used.(What are the Variables Scope Rules in C Programming)

Example of Global Variables in C

/* C Scope Rules - Global Variable Example */
#include<stdio.h>
int count;     // this count variable is global
int num1(void);
int num2(void);
int main()
{
   
   count = 10;
   num1();
   return 0;
}
int num1(void)
{
   num2();
   printf("count is %d", count);   // this will print 10
}
int num2(void)
{
   int count;   // this is local variable having first priority
   for(count=1; count<5; count++)
   {
      putchar('.');
   }
}

Output of the above example

….count is 10

Explanation

The global variables are used throughout the program. If you declare and initialize a variable with the same name, the local variable is given high priority.

As a result, the value assigned to the variable within the local block or functions will be retained until the block or functions is closed.

It means that local variables will be created to disguise the global variables, and they will be produced upon block enter and removed upon block or function departure.

So, while a program’s local and global variables can have the same name, the value of a local variable within a function takes precedence.

You can try to test here the example above!

Another Example of Global Variables in C

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

Output of the above example

value of x = 10

You can try to test here the example above!

Formal Parameters in C

Function parameters, also known as formal parameters, are treated the same as local variables within that function, and they take precedence over global variables.

Example of Global Variables in C

/* C Scope Rules - Format Paramter Example */
#include<stdio.h>
int x = 20;    // global variable declaration
int main()
{
   /* local variable declaration in main() function */
   int x = 10;
   int y = 20;
   int z = 0;
   
   printf("value of x inside main() function = %d\n", x);
   z = sum( x, y);
   printf("value of z inside main() function = %d\n", z);
   return 0;
}
int sum(int x, int y)
{
    printf ("value of x inside sum() function = %d\n", x);
    printf ("value of y inside sum() function = %d\n", y);
    return x + y;
}

Output of the above example

value of x inside main() function = 10
value of x inside sum() function = 10
value of y inside sum() function = 20
value of z inside main() function = 30

Explanation

Variables x and y within the function sum() in the main() function are only formal arguments, with a holding 10 and x holding 20. As a result, the sum() function receives the values x and y.

The sum function prints the values of x and y. The sum() method, which is initialized to z, then returns the sum of x and y. The number 30 is then displayed on the screen.

You can try to test here the example above!

Initializing Local and Global Variables

When you define a local variable, the system does not initialize it; you must do so yourself. When you define global variables like follows, the system will automatically initialize them:

Data TypeInitial Default Value
char‘\0’
int0
float0
double0
pointerNULL

It is important programming practice to correctly initialize variables; otherwise, your program may yield unexpected results since uninitialized variables will accept the first trash value available at their memory location.

Conclusion

If a variable’s scope is global, it means it can be accessed from anywhere in the program or from anywhere else in the world. It signifies that there are no variables with that name outside of that function until a new variable with the same name is defined. In the case of formal parameters, it is similar to a local variable that can only be known by that function.

About Next Tutorial

In the next following post, I’ll create a Arrays in C and try to explain its many components in full details. I hope you enjoy this post on What are the Variables Scope Rules in C Programming, in which I attempt to illustrate the language’s core grammar.

Leave a Comment