C++ Call by Value & Reference
Call by Value
When a function is called by value, a copy of the original argument is passed to the called function. The copied argument occupy separate memory location than the actual argument. If any changes were done to values inside the function, it is only visible inside the function. Their values remain unchanged outside it.
Example:-
#include <iostream> using namespace std; int sum(int num1, int num2); int main(){ int a = 100, b=12, result; result= sum(a, b); /* call by value */ cout << "Sum of two numbers value is :" << result << endl; return 0; } int sum(int num1, int num2) { int sum=num1+num2; return sum; }
Call by Reference
The address of argument is copied instead of value. Within the function, the address of argument is used to access the actual argument. If any changes are done inside the function to values, it is visible both inside and outside the function.
Example:-
#include <iostream> using namespace std; void sum(int *a, int *b) { int sum; sum=*a+*b; cout << "Sum of two numbers value is :" << sum << endl; } int main(){ int a = 100,b=12,result; sum(&a, &b); /* calling a function to get sum value */ return 0; }
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.