Here, we have a basic program example to add two numbers using call by reference in C and C++.
Code to add two numbers using call by reference in C language
#include <stdio.h>
long addTwoNumbers(long *, long *);
int main()
{
long num1, num2, sum;
printf(" Input the first number : ");
scanf("%ld", &num1);
printf(" Input the second number : ");
scanf("%ld", &num2);
sum = addTwoNumbers(&num1, &num2);
printf(" The sum of %ld and %ld is %ld\n\n", num1, num2, sum);
return 0;
}
long addTwoNumbers(long *n1, long *n2)
{
long sum;
sum = *n1 + *n2;
return sum;
}
Code to add two numbers using call by reference in C++ language
#include<iostream>
using namespace std;
void sum(int num1, int num2, int *s) {
*s = num1 + num2;
}
int main() {
int num1, num2, s;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
sum(num1, num2, &s);
cout << "Sum is: " << s;
return 0;
}