Local scope of variables

Lesson Details:
June 29, 2020


I: Introduction

The following is an article about programming languages.

II: Body

A: Local scope of variables

1. Local scope means that a variable can be accessed within the function but cannot be accessed outside the function.

2. Some languages like C and C++ support this feature. These languages use curly brackets to define the local scope of a variable.

3. Let us look at a simple example of a program in C language.

4. In the above program, we have defined a variable called "var" inside a function called "func1()". So, the variable "var" is accessible only inside the function "func1()". Now, let us call this function from another function.

5. In the above program, we have tried to access the variable "var" from outside the function "func1()". As we have already seen that the variable var is not accessible from outside the function, so we get an error message as shown below.

6. The error message is saying that "var is not declared". This is because, we have tried to access a variable which is not declared outside the function.

7. If we want to make a variable accessible outside a function, then we need to use a special keyword called as static as shown below.

8. In the above program, we have used static keyword before defining a variable called as "var". This makes the variable "var" accessible from anywhere in the program. So now, if we try to access the variable from outside the function then it will work fine.

A: Learn basic python programming for beginners

loader
Course content