Home > Article > Backend Development > Explain the scoping rules related to functions in C language
Scope rules are related to the following factors:
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.
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; }
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.
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; }
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!