Scope Rules

14 – Scope Rules in C Programming Language

In this chapter, we will learn Scope Rules.

In any programming language, a scope is a region of the program where a defined variable can have its existence & beyond that variable it cannot be accessed.
There are three places in C programming language, where variable can be declared:

  • Inside a function or block which is called local variables.
  • Outside of all function which is called global variables.
  • In the definition of function parameters which are called formal parameters.

Now let us understand what is local & global variables & formal parameters.

Local variable

Which variables are declared inside a function or block are called local variables. They can be used by only statements which are inside the function or bock of code.
The below example shows that how local variables are used. Here all the variables a,b & c are local to main() function.

Global Variables

The Global Variables are defined outside a function, on top of the program usually. Global variables hold their values throughout the lifetime of the program & they can be accessed inside any function which are defined for the program.

A global variable can be accessed by any function. Global variable is available for use throughout the entire program after its declaration.
The below program shows that how global variables are used in a program.

A program which have same name for local & global variables but the value of local variables inside the function will take preference.
For Example:

Formal Parameters

Formal parameters are treated as local variables with-in a function & they take precedence over global variables.
For Example:

When the above code is compiled & executed, it produces the following result:

Initializing Local & Global Variables

When a local variable is defined, you must initialize it by yourself because it is not initialized by the system. Global variables are initialized automatically by the system, when you define them as follows:

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

That’s the end of Scope Rules.

Click Here for more Articles:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.