Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

In C, the scope of a variable refers to the region of the program where the variable can be accessed or modified. There are mainly three types of variable scope in C:

1. Local Scope:

A variable with local scope is declared within a block of code, such as a function, and is only accessible within that block.

Example:

#include <stdio.h>

void exampleFunction() {
    int localVar = 10;  // localVar has local scope
    printf(“Local Variable: %dn”, localVar);
}

int main() {
    // localVar is not accessible here
    exampleFunction();
    return 0;
}

 

2. Global Scope:

A variable with global scope is declared outside of any function or block and can be accessed throughout the entire program.

Example:

#include <stdio.h>

int globalVar = 20; // globalVar has global scope

void exampleFunction()
{
    printf(“Global Variable: %dn”, globalVar);
}

int main()
{
    printf(“Global Variable: %dn”, globalVar);
    exampleFunction();
    return 0;
}

 

3. Function Parameter Scope:

Parameters passed to a function have a scope limited to that function.

Example:

#include <stdio.h>

void printNumber(int num)
{
    // num has local scope within this function
    printf(“Number: %dn”, num);
}

int main()
{
    int mainVar = 30; // mainVar has local scope within main
    printNumber(mainVar);
    return 0;
}

 

It’s important to note that variables declared within a block (local scope) can have the same name as a variable in a different block (including parameters in functions) without causing conflicts. Each variable has its own scope, and the compiler resolves references based on the closest scope.