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

What are the function scoping rules in C programming?

王林
王林forward
2023-08-31 08:37:061356browse

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);
}

Output

p =30, r = 50
r = 50

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;
}

Output

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

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;
}

Output

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

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!

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