Home > Backend Development > C++ > body text

Explain the scoping rules related to functions in C language

王林
Release: 2023-09-17 19:57:09
forward
834 people have browsed it

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;
}
Copy after login

Output

The output is as follows −

Before swapping a=10, b=20
After swapping a = 10, b=20
Copy after login
  • 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;
}
Copy after login

Output

The output is as follows −

Before swapping a = 10, b =20
After swapping a = 20, b = 10
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template