Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE) PDF Download

What is Scope of a Variable?

The scope of a variable defines the region in the code where that variable can be referenced or used. It includes the current state of the variables along with their values. The scope of a variable depends on where it is declared in the program. Once declared, the variable can be accessed and manipulated as needed. Understanding how a variable's value is accessed and used within its scope is crucial for determining the program's behavior.

When the program exits the scope where a variable is defined, the memory allocated to that variable is typically released, rendering the variable inaccessible. This efficient management of resources prevents accidental access or modification of the variable’s data outside its intended scope.

Local Scope of Variables in C – Nested Blocks

In this section, you'll learn how local variables work in C. You'll first code a couple of examples, and then you'll generalize the scoping principle.
Example 1:

#include <stdio.h>

int main() 

{

    int my_num = 7;

    {

        //add 10 my_num

        my_num = my_num +10;

        //or my_num +=10 - more succinctly

        printf("my_num is %d",my_num);

    }

        return 0;

}

Let's understand what the above program does.
In C, you delimit a block of code by {} . The opening and closing curly braces indicate the beginning and the end of a block, respectively.
The main() function has an integer variable my_num that's initialized to 7 in the outer block. There's an inner block that tries to add 10 to the variable my_num. Now, compile and run the above program. Here's the output:

//Output

my_num is 17

You can see the following:

  • The inner block is able to access the value of my_num that's declared in the outer block, and modify it by adding 7 to it.
  • The value of my_num is now 17, as indicated in the output.

Example 2:

#include <stdio.h>

int main() 

{

    int my_num = 7;

    {

        int new_num = 10;

    } 

    printf("new_num is %d",new_num); //this is line 9

    return 0;

  • In this program, the main() function has an integer variable my_num in the outer block.
  • Another variable new_num is initialized in the inner block. The inner block is nested inside the outer block.
  • We're trying to access and print the value of inner block's new_num in the outer block.

If you try compiling the above code, you'll notice that it doesn't compile successfully. And you'll get the following error message:
Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE)

This is because the variable new_num is declared in the inner block and its scope is limited to the inner block. In other words, it is local to the inner block and cannot be accessed from the outer block.

Based on the above observations, let's write down the following generic principle for local scoping of variables:
{

    /*OUTER BLOCK*/

      {

             //contents of the outer block just before the start of this block

        //CAN be accessed here

       /*INNER BLOCK*/
}

       //contents of the inner block are NOT accessible here

 }

Local Scope of Variables in C – Different Blocks

In the previous example, you learned how variables inside the nested inner block cannot be accessed from outside the block.
In this section, you'll understand the local scope of variables declared in different blocks.

#include <stdio.h>

int main()

{

    int my_num = 7;

    printf("%d",my_num);

    my_func();

    return 0;

}

void my_func()

{

    printf("%d",my_num);

}

In the above example,

  • The integer variable my_num is declared inside the main() function.
  • Inside the main() function, the value of my_num is printed out.
  • There's another function my_func() that tries to access and print the value of my_num.
  • As program execution starts with the main() function, there's a call to my_func() inside the main() function.

Now compile and run the above program. You'll get the following error message:

Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE)

If you notice, on line 13, the function my_func() tried accessing the my_num variable that was declared and initialized inside the main() function.

  • Therefore, the scope of the variable my_num is confined to the main() function, and is said to be local to the main() function.

We can represent this notion of local scope generically as follows:

{

    /*BLOCK 1*/

    // contents of BLOCK 2 cannot be accessed here

}

{

    /*BLOCK 2*/

    // contents of BLOCK 1 cannot be accessed here

 }

Global Scope of Variables in C

So far, you've learned about local scope of C variables. In this section, you'll learn how you can declare global variables in C.
Let's start with an example.

#include <stdio.h>

int my_num = 7;

int main()

{

    printf("my_num can be accessed from main() and its value is %d\n",my_num);

    //call my_func

    my_func();

    return 0;

}

void my_func()

{

  printf("my_num can be accessed from my_func() as well and its value is %d\n",my_num);

}

In the above example,

  • The variable my_num is declared outside the functions main() and my_func().
  • We try to access my_num inside the main() function, and print its value.
  • We call the function my_func() inside the main() function.
  • The function my_func() also tries to access the value of my_num, and print it out.

This program compiles without any error, and the output is shown below:

Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE)

In this example, there are two functions – the main() and my_func().
However, the variable my_num is not local to any function in the program. Such a variable that is not local to any function is said to have global scope and is called a global variable.
This principle of global scope of variables can be summarized as shown below:

//all global variables are declared here

function1()

    {

    // all global variables can be accessed inside function1
    }

function2()

    {

    // all global variables can be accessed inside function2

    }

The document Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE) is a part of the Computer Science Engineering (CSE) Course Programming and Data Structures.
All you need of Computer Science Engineering (CSE) at this link: Computer Science Engineering (CSE)
119 docs|30 tests

Top Courses for Computer Science Engineering (CSE)

FAQs on Scope of Variable - Programming and Data Structures - Computer Science Engineering (CSE)

1. What is the full form of GATE exam?
Ans. The full form of GATE exam is Graduate Aptitude Test in Engineering.
2. How many papers are there in the GATE exam?
Ans. The GATE exam consists of 27 papers covering various engineering disciplines and general aptitude.
3. Can candidates from non-engineering backgrounds appear for the GATE exam?
Ans. Yes, candidates from non-engineering backgrounds can also appear for the GATE exam, provided they meet the eligibility criteria for the specific paper they are interested in.
4. What is the validity period of a GATE score?
Ans. The GATE score is valid for three years from the date of announcement of the results.
5. How many times can a candidate attempt the GATE exam?
Ans. There is no limit on the number of attempts for the GATE exam. Candidates can appear for the exam as many times as they wish to improve their score.
119 docs|30 tests
Download as PDF
Explore Courses for Computer Science Engineering (CSE) exam

Top Courses for Computer Science Engineering (CSE)

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

shortcuts and tricks

,

video lectures

,

Exam

,

practice quizzes

,

pdf

,

Sample Paper

,

Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE)

,

Summary

,

mock tests for examination

,

Previous Year Questions with Solutions

,

study material

,

Objective type Questions

,

Important questions

,

Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE)

,

Free

,

past year papers

,

Viva Questions

,

Extra Questions

,

Scope of Variable | Programming and Data Structures - Computer Science Engineering (CSE)

,

ppt

,

Semester Notes

,

MCQs

;