Explain scope rules related to the functions in C language



Scope rules are related to the following factors −

  • Accessibility of a variables.
  • Period of existence of a variable.
  • Boundary of usage of variables.

Scope rules related to functions are as follows

  • Function which is a self-contained block that performs a particular task.

  • Variables that are declared within the function body are called local variables.

  • These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main functions too.

  • The existence of local variables ends when the function completes its specific task and returns to the calling point.

Example 1

Following is the C program for scope rules related to functions

#include<stdio.h> main ( ){    int a=10, b = 20;    printf ("before swapping a=%d, b=%d", a,b);    swap (a,b);    printf ("after swapping a=%d, b=%d", a,b); } swap (int a, int b){    int c;    c=a;    a=b;    b=c; }

Output

The output is stated below −

Before swapping a=10, b=20 After swapping a = 10, b=20
  • Variables that are declared outside the function body are called global variables.

  • These variables are accessible by any of the functions.

Example 2

Here is another C program for scope rules related to functions

include<stdio.h> int a=10, b = 20; main(){    printf ("before swapping a=%d, b=%d", a,b);    swap ( );    printf ("after swapping a=%d, b=%d", a,b); } swap ( ){    int c;    c=a;    a=b;    b=c; }

Output

The output is stated below −

Before swapping a = 10, b =20 After swapping a = 20, b = 10
Updated on: 2021-03-15T15:22:35+05:30

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements