C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Learn to use References

By David Bolton, About.com

2 of 7

Using References in Function Parameters

C++ added pass by reference using reference parameters. In effect, by defining a parameter like this
afunction(int & value) {
within the function, value is actually the external variable and any changes to value affect the external variable.
// 8_2.cpp :
//
#include "stdafx.h"
#include <iostream>

void testfunction(int & value) {

value++;
}

int main(int argc, char* argv[])
{
int a=10;
int b=20;
testfunction(a) ;
testfunction(b) ;
std::cout << "a = " << a << " b = "<< b << std::endl;
return 0;
}
In example 8_2, testfunction is called twice, on variables a and b. The result is
a = 11 b = 21
Showing that a and b were both changed by the calls to testfunction.

Const Parameters

If you put the word const before the type then any attempt to change the parameter will cause a compilation error. You've indicated to the compiler that it is a const, so the compiler will prevent it being altered. But as we've just discovered a way to alter variables passed in to functions, why try to prevent that?

The Answer : for single variables like ints or even floats, there is little point in making them const and reference. Might as well just pass them by value. . For larger types such as structs and arrays though it makes a lot of sense, because if passed by value they have to be copied. Pass by reference doesn't make a copy, it just passes in a pointer. This is far faster to execute.

On the next page : Learn about references and return values.

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Using References in Function Parameters

©2009 About.com, a part of The New York Times Company.

All rights reserved.