Search This Blog

Thursday, January 4, 2024

Function in C Part 3:Scope of Variables:

 

Scope of Variables:

  • A scope is a region of the program, and the scope of variables refers to the area of the program where the variables can be accessed after its declaration.

  • The scope of the variable is simply lifetime of a variable. It is block of code under which a variable is applicable or alive. 

  • There are three places where variables you can declare variable programming language:

    1. Inside a function or a block: Local variables

    2. Outside of all functions: Global variables

    3. In the definition of function parameters: Formal parameters

Local Variables:

  • Variables that are declared inside a function or block are called local variables. 

  • The local variables exist only inside the block in which it is declared.

  • The local variable exists until the block of the function is under execution. After that, it will be destroyed automatically.

  • Example of  Local Variable 

public int add(){ 

int a =4; 

int b=5; 

return a+b; 

Here, 'a' and 'b' are local variables

#include<stdio.h>

int main()

{

    int a = 100;

    {

        int a = 10;  

        printf("Inner a = %d\n", a);

    }

    printf("Outer a = %d\n", a);

    return 0;

}


Output:

Inner a = 10

Outer a = 100

Global Variables :

  • Global variables are defined outside a function, usually on top of the program (Global declaration section).

  • It has a global scope means it holds its value throughout the lifetime of the program.

  • Any function can access and modify global variables. That is, a global variable is available for use throughout your entire program after its declaration. 

  • Global variables are automatically initialized to 0 at the time of declaration. 

  • Example:

int a =4; int b=5; 

public int add()

return a+b;

 }

 Here, 'a' and 'b' are global variables.

#include<stdio.h>


void func_1();

void func_2();


int a, b = 10;  // declaring and initializing global variables


int main()

{

    printf("Global a = %d\n", a);

    printf("Global b = %d\n\n", b);


    func_1();

    func_2();


    return 0;

}


void func_1()

{

    printf("From func_1() Global a = %d\n", a);

    printf("From func_1() Global b = %d\n\n", b);

}

void func_2()

{

    int a = 5;

    printf("Inside func_2() a = %d\n", a);

}


Output:


Global a = 0

Global b = 10


From func_1() Global a = 0

From func_1() Global b = 10


Inside func_2() a = 5


No comments:

Post a Comment

Function in C Part 4: Recursion Function, Nested Functions

  Recursion Function A function that calls itself is known as a recursive function. And, this technique is known as recursion. The recursion...