What are the scope rules to functions in C programming?

CServer Side ProgrammingProgramming

Local scope

Local scope specifies that variables defined within the block are visible only in that block and invisible outside the block.

Global scope

Global scope specifies that variables defined outside the block are visible up to end of the program.

Example

#include<stdio.h>
int r= 50; /* global area */
main (){
   int p = 30;
   printf (“p=%d, r=%d” p,r);
   fun ();
}
fun (){
   printf (“r=%d”,r);
}

Output

p =30, r = 50
r = 50

Scope rules related to functions

  • A Function is a block of statements that performs a particular task.

  • Variables that are declared within the body of a function 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 also

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

Example

#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

Before swapping a=10, b=20
After swapping a = 10, b=20

Variables declared outside the body of a function are called global variables. These variables are accessible by any of the functions.

Example

#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

Before swapping a = 10, b =20
After swapping a = 20, b = 10
raja
Published on 08-Mar-2021 17:43:49
Advertisements