Home  >  Article  >  Backend Development  >  Explain the scoping rules related to functions in C language

Explain the scoping rules related to functions in C language

王林
王林forward
2023-09-17 19:57:09832browse

Explain the scoping rules related to functions in C language

Scope rules are related to the following factors:

  • Accessibility of variables.
  • The existence period of the variable.
  • Usage boundaries of variables.

The scoping rules related to functions are as follows

  • A function is a self-contained block that performs a specific task.

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

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

  • The existence of a local variable ends when the function completes its specific task and returns to the calling site.

Example 1

The following is the C program related to the scope rules related to the function:

#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 as follows −

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

  • These variables can be accessed by any function.

Example 2

This is another C program with function-related scoping rules.

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 as follows −

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

The above is the detailed content of Explain the scoping rules related to functions in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more