DEV Community

Cover image for Types of Variables Based on Scope
Mukesh Kumar
Mukesh Kumar

Posted on

Types of Variables Based on Scope

🎙️ Introduction

Hello everyone!

In this chapter, we are going to understand an important concept in C programming — Types of Variables Based on Scope.

In the previous lesson, we learned what a variable is and how it stores data. But now the question is:

👉 Can we use every variable everywhere in a program...Read More

🔹 Step 1: What is Scope?

Scope defines the area of a program where a variable can be accessed or used.

In simple words:

Scope tells us where a variable is visible and usable inside the program.

If a variable is declared in one part of the program, it...Read More

🔹 Step 2: Local Variables

A local variable is declared inside a function or inside a block.

It can only be used within that function or block where it is declared.

Once the function finishes execution, the local variable is destroyed automatically.

Example Explanation:

If we declare a variable inside the main function, it can...Read More

🔹 Step 3: Global Variables

A global variable is declared outside all functions, usually at the top of the program.

It can be accessed by all functions in the program.

That means:

Its scope is the entire program.

It is visible everywhere.

Example Explanation:

If a variable is declared before the main function...Read More

🔹 Step 4: Comparison Between Local and Global Variables

Let us compare them clearly:

Local Variable:

Declared inside a function.

Accessible only inside that function.

Lifetime is limited to function execution...Read More

🔹 Step 5: Block Scope (Inside Curly Braces)

In C, even inside a function, if we declare a variable inside curly braces { }, it is accessible only inside that block.

For example:

If we declare a variable inside an if statement block, it...Read More

🔹 Step 6: Why Scope is Important?

Understanding scope helps us:

Avoid variable conflicts.

Prevent accidental data modification.

Improve memory management.

Write clean and structured programs.

If two functions use the same variable name but both are...Read More

📌 Summary

In this chapter, we learned:

Scope defines where a variable can be accessed.

Based on scope, variables are:

Local Variables

Global Variables

Local variables are limited to a function...Read More

Top comments (0)