1 Answers
Similar to parameter passing, a function can return in 3 ways
- Return by value
- Return by address
- Return by reference
Return by Value
int sum(int, int);
int main() { int a = 10, b = 20, c; c = sum(a, b); return 0; } int sum(int x, int y) { int z; z = x + y; return z; } // z --> CPU reg like accumulator // accumuator --> c
Return by Address
int *fetchp(void); int main() { int *ptr = fetchp();
//some code
//access *ptr return 0; } int* fetchp(void) { int val = 100; return &val; }
Return by Reference
#include <iostream> int main() { int &ref = fetchr();
//some code
//access ref return 0; } int& fetchr(void) { int val = 100; return val; }