Home > Backend Development > C++ > What are the function scoping rules in C programming?

What are the function scoping rules in C programming?

王林
Release: 2023-08-31 08:37:06
forward
1398 people have browsed it

What are the function scoping rules in C programming?

Local scope

The variables defined in the local scope specified block are only visible within the block and not visible outside the block.

Global scope

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

Example

#include<stdio.h>
int r= 50; /* global area */
main (){
   int p = 30;
   printf (&ldquo;p=%d, r=%d&rdquo; p,r);
   fun ();
}
fun (){
   printf (&ldquo;r=%d&rdquo;,r);
}
Copy after login

Output

p =30, r = 50
r = 50
Copy after login

Scope rules related to functions

  • Functions perform specific tasks statement block.

  • Variables declared within the body of a function are called local variables

  • These variables exist only inside the specific function that created them. Neither other functions nor the main function know about them

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

Output

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

Variables declared outside the function body are called global variables. These variables can be accessed through any function.

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

Output

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

The above is the detailed content of What are the function scoping rules in C programming?. 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