In C programs, functions that have parameters are invoked in one of two ways:
1). Call by value
2). Call by reference
These will be illustrated through the example of a program called computer that takes two numbers and a mathematical operator as input and perfoms the appropriate arithmetic operation on the numbers.
Call by Value
Consider the following code for the problem statement memtioned:
main()
{
int num1,num2;
char operator;
printf("Enter 2 numbers and an operator\n");
scanf("%d%d%c", &num1, &num2, &operator);
fflush(stdin);
calc(num1, num2, operator);
}
calc(val1, val2, oper)
int val1, val2;
char oper;
{
switch(oper)
{
case '+' : printf("%d", val1 + val2);
break;
case '-' : printf("%d", val1 - val2);
break;
case '*' : printf("%d", val1 * val2);
break;
case '/' : printf("%d", val1 / val2);
break;
default: printf("Invalid operator \n");
}
}
In this program, values entered for the variables num1, num2 and operator in the main() function are passed to the function calc().
0 comments:
Post a Comment