Translate

Friday, May 8, 2020

What is Scope of Global and Local Variable in C ?

Local Variable:-  The variables that defined within the body of a function or a block, are called local variable. In simple words, The scope of  a local variable is limited to the function in which it is defined. 

Syntax:
function(a, b)
int a, b;
{
int x, y;   /*Local Variable*/
/*body of the function*/
}
Example:
#include<stdio.h>
#include<conio.h>
  void main()
{
  int a, b, sum; /*Local Variable*/

/* Printf() outputs the values to the screen whereas scanf() receive them from the keyboard.   and  &   is a address used in scanf(). */

 printf("enter  first no=");
  scanf("%d", & a);
  printf("enter second no=");
  scanf("%d", & b);
  sum= a+b;
  printf("Sum of two number is =%d",sum);
  getch();
}

Output:












Global Variable:- Global Variable are defined outside the main() function block. All functions in the program can access and modify global variables. Its's very useful if it is to be used by many functions in the program. this variables are automatically initialized by 0 at the time of declaration.

Syntax: 
int x, y; /*Global Variable*/
main()
{
x=5;
function1();
}
function1();
{
int sum;
sum=x+y;
}

Example:
#include<stdio.h>
#include<conio.h>
int sum;  void main()
{
  int a, b; /*Local Variable*/

/* Printf() outputs the values to the screen whereas scanf() receive them from the keyboard.   and  &   is a address used in scanf(). */

 printf("enter  first no=");
  scanf("%d", & a);
  printf("enter second no=");
  scanf("%d", & b);
  sum= a+b;
  printf("Sum of two number is =%d",sum);
  getch();
}

Output:











Click here, for All Important Questions




c.

No comments:

Post a Comment

C program to make a calculator using the switch statement.

/*perform arithmetic calculation on integers in C language*/ #include<stdio.h> #include<conio.h> void main() {     char op;     ...