Global Variable in C Programming
A local variable is one that is declared inside a function and can only be used by that function. If you declare a variable outside all functions then it is a global variable and can be used by all functions in a program.// Global variables
int a;
int b;
int Add()
{
return a + b;
}
int main()
{
// Local variable
a = 5;
b = 7;
answer = Add();
printf("%d\n",answer);
return 0;
}
Call by Value and Call by reference
The arguments passed to function can be of two types namely
1. Values passed / Call by Value
2. Address passed / Call by reference
The first type refers to call by value and the second type refers to call by reference. For instance, consider program 1:
main()
{
int x=50, y=70;
interchange(x,y);
printf(“x=%d y=%d”,x,y);
}
interchange(x1,y1)
int x1,y1;
{
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(“x1=%d y1=%d”,x1,y1);
}
Here the value to function interchange is passed by value.
Consider program 2
main()
{
int x=50, y=70;
interchange(&x,&y);
printf(“x=%d y=%d”,x,y);
}
interchange(x1,y1)
int *x1,*y1;
{
int z1;
z1=*x1;
*x1=*y1;
*y1=z1;
printf(“*x=%d *y=%d”,x1,y1);
}
Here the function is called by reference. In other words, the address is passed by using symbol &, and the value is accessed by using symbol *.
The main difference between them can be seen by analyzing the output of program1 and program2.
The output of program1 that is call by value is
The output of program1 that is call by value is
x1=70 y1=50
x=50 y=70
But the output of program2 that is call by reference is
*x=70 *y=50
x=70 y=50
This is because in the case of call by value the value is passed to a function named interchange and there the value got interchanged and got printed as
x1=70 y1=50
and again since no values are returned back and therefore original values of x and y as in the main function namely
x=50 y=70 got printed.
Post A Comment:
0 comments so far,add yours