Monday, 16 March 2015

C++ References in functions with examples

C++ References in functions with examples:

References are frequently used as  function arguments and function return values. When a reference is used as a function argument, any modification to the reference inside the function will cause changes to the argument outside the function.

  If you return a reference from a function, you must take the same care as if you return a pointer from a function. Whatever the reference is connected to shouldn't go away when the function returns, otherwise you’ll be referring to unknown memory.

Let us see the working example to understand about the references used like arguments and return values.

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int* MyFun(int* inVal) {
  return inVal;
int& MyFun1 (int& inVal) {
  return inVal;
int& MyFun2 () {
  static int inVal;
  return inVal;
int main ()
  int iVal = 0;
  MyFun (&iVal);
  cout << iVal << endl;
  MyFun1 (iVal);
  cout << iVal << endl;
  int iRes = MyFun2 ();
  cout << iRes << endl;
  getchar ();
  return 0;

The call to MyFun ( ) doesn’t have the convenience and cleanliness of using references, but it’s clear that an address is being passed. In the call to MyFun1 ( ), an address is being passed.

No comments: