Wednesday 13 February 2013

Call by Reference in C Programming Language



Call by reference means that the called function should be able to refer to the variables of the caller function directly, and not create its own copy of the values in different variables. This would be possible only if the address of the variables are passed as parameters to the function.

Consider the same program written using call by reference:

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, the addresses of the variables num1, num2 and operator are passed as parameters to the function calc(), instead of their values.

0 comments:

Post a Comment

Powered by Blogger.