Parameter Passing in C
Parameter Passing in C
Parameters are the data values that are passed from calling function
to called function.
Actual Parameters
Formal Parameters
Call by Value
Call by Reference
Call by Value
#include <stdio.h>
int main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
num1 = 10 ;
num2 = 20 ;
In the above example program, the variables num1 and num2 are called
actual parameters and the variables a and b are called formal
parameters. The value of num1 is copied into a and the value of num2
is copied into b. The changes made on variables a and b does not
effect the values of num1 and num2.
Call by Reference
#include <stdio.h>
int main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
num1 = 10 ;
num2 = 20 ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Scope of Variable in C
#include <stdio.h>
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}
In the above example program, the variables num1 and num2 are
declared as global variables. They are declared before the main()
function. So, they can be accessed by function main() and other
functions that are defined after main(). In the above example, the
functions main(), addition(), subtraction() and multiplication() can
access the variables num1 and num2.
#include <stdio.h>
int main(){
void addition() ;
addition() ;
}
void addition()
{
int num1, num2 ;//local variables
int sumResult ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
#include <stdio.h>
int main(){
void addition(int, int) ;
int num1, num2 ;
num1 = 10 ;
num2 = 20 ;
addition(num1, num2) ;
}
void addition(int a, int b)
{
int sumResult ;
sumResult = a + b ;
printf("\naddition = %d", sumResult) ;
}