Home > Articles > Programming > C/C++

This chapter is from the book

3.3 References with Functions

Chapter 2 introduces references as aliases (see "References" on page 41). Although aliases have some advantages over pointers, the real power of references is with functions. This section shows you why references are beneficial with function arguments and return values. We also show you how to use references to pointers in function arguments.


References as Function Arguments

Function arguments may be references. The formats are

 Type function_name(Type &);      // prototype

 Type function_name(Type & arg)     // definition
 {
  function body
 }

Function calls with arguments initialize a reference and create an alias. Inside the body of the function, the alias arg refers to the corresponding argument in the caller's program. Expressions in function statements with alias names as lvalues (such as assignments or increment operators) modify the argument in the caller. Expressions with aliases as rvalues provide read access to function arguments.

References may appear with default arguments only if you initialize them to statics or globals (see "static" on page 125). Here are several examples.

 static double dval = 5.6;         // static
 char f(double & d = 5.6);         // illegal
 char g(double & d = dval);         // legal

Why use references instead of pointers in function arguments? To illustrate, let's write a function called bump(), whose job is to increment its integer argument by one. Our first approach doesn't work, but it tells us what we need.

 inline void bump(int m) {
  ++m;              // increment by one
 }

 int num = 10;
 bump(num);            // call by value
 cout << num << endl;       // displays 10

We don't increment num because we pass it by value to bump() and modify only a local variable (m). Let's try it again with a pointer argument instead.

 inline void bump(int *p) {
  ++*p;            // increment by one
 }

 int num = 10;
 bump(&num);           // call by address
 cout << num << endl;      // displays 11

This time we increment num correctly. We pass num by address (&num) so that bump() can modify it using the compact pointer expression ++*p. (This expression increments what p points to.) Although this works, it's easy to confuse the previous expression with *p++, which compiles but does not increment num! (Here, we increment the pointer and not what it points to; see "Compact Pointer Expressions" on page 63.)

These kinds of mistakes can't happen with references because pointer expressions are unnecessary. Here's the code for bump() with references.

 inline void bump(int & m) {
  ++m;             // increment by one
 }

 int num = 10;
 bump(num);           // call by reference
 cout << num << endl;      // displays 11

This looks like a call by value, except that the function definition makes the compiler pass a reference to bump(), rather than a value. Inside bump(), the compiler generates the code to increment num, using the alias m. Designing bump() with references makes it easy to call (no &) and easy to write (no pointer expressions inside the body of the function).

NOTE

Don't confuse references with pointers in function signatures (int * is not the same as int &). When you pass pointers to functions that expect references (or vice versa), you will get either linkage errors or compilation errors.

Sometimes you need to pass structure types as arguments to functions. We usually do not want to pass these types by value because programs perform poorly when the compiler creates local copies of large structures inside functions. Although function calls with structure pointers would improve performance here, you must use pointer notation (* or ->) to access data members inside your functions. References, on the other hand, let you access data members by using the dot operator (.) and yet perform just as well.

The formats for passing structure types in function prototypes are

 Type function_name(struct_type &);
 Type function_name(const struct_type &);

With constant structure arguments, the compiler reports errors if function_name modifies a data member. Both formats are efficient with struct types because we avoid structure copies during function calls.

The following program illustrates references to structures with function arguments.

Listing 3.8 Constant reference arguments

 // ref.C - const reference arguments
 #include <iostream.h>

 const int MaxBuf = 20;
 struct block {
  char buf[MaxBuf];

  int used;
 };

 int main()
 {
  void display(const block &);      // prototype for display()
  block data;
  int i;

  data.used = 5;
  for (i = 0; i < data.used; i++)     // assign some values
    data.buf[i] = i + 'a'
  display(data);             // call by reference

  data.used = MaxBuf;

  for (i = 0; i < data.used; i++)
    data.buf[i] = i + 'a';
  display(data);             // call by reference
  return 0;
 }

 void display(const block & blockref) {
  for (int i = 0; i < blockref.used; i++)
    cout << blockref.buf[i] << ' ';
  cout << endl;
 }

 $ ref
 a b c d e
 a b c d e f g h i j k l m n o p q r s t

The main() program creates a data structure of type block, and for loops fill its data member array (buf) with characters. Data member used retains a count of the number of valid array elements. The program calls display() twice to print out array elements. Inside display(), we declare blockref a constant reference to block, making calls to display() efficient (no local copies) and safe (no modifications).

NOTE

Use const Type & inside functions signatures that don't modify their structure or union arguments. Judicious use of this idiom makes function design consistent, efficient, and safe.

References as Function Return Types

Functions may return references. The formats are

 Type & function_name(signature);
 const Type & function_name(signature);

The compiler actually returns a pointer in both formats, but a caller does not use pointer notation (*, ->) with the result. In the second format, const makes the compiler report errors if a caller tries to modify the result as an lvalue. Returning references from functions is important with structure types, for the same reason we gave for function arguments earlier: performance. When you return a reference to a structure type from a function call, the compiler returns a pointer instead of a copy.

Another use of references with function returns is cascading. This technique allows you to embed function calls, as follows.

 function_name(function_name(function_name(args))); 

To see why references are appealing with cascading, let's modify our pointer version of bump() from the previous section.

 inline int *bump(int *p) {
  ++*p;                 // increment by one
  return p;               // return pointer
 }

 int num = 10;
 cout << *bump(bump(&num)) << endl;    // displays 12

We embed bump() calls in the cout statement because bump() now returns its first argument, which is a pointer to an integer. We must, however, use & to pass the address of num in the first call to bump() and use * to dereference the return value from the second bump() call. If we forget to dereference (*), the program still compiles and runs, but displays an address (pointer to an integer) instead of the correct answer (12).

References make this simple. Here's the code.

 inline int & bump(int & m) {
  return ++m;               // increment by one
 }

 int num = 10;
 cout << bump(bump(num)) << endl;      // displays 12

With references, the compiler supplies the pointers to pass function arguments and return values. Embedded calls to bump(), therefore, do not require pointer notation.

NOTE

Make sure you do not return dangling references to local, nonstatic variables defined inside functions. Suppose, for example, we modify bump() as follows.

 inline int & bump(const int & m) {            // return reference
  int result = m + 1;                   // local variable
  return result;
 }

This version of bump() returns an incremented value without modifying its argument. We return, however, a reference to a local variable (on the stack), whose memory location no longer exists when the function returns! Fortunately, many C++ compilers warn you about dangling references (and dangling pointers, too). Our machine, for example, displays the following warning message.

 warning: reference to local variable returned 

The correct approach for this version of bump() is to return an integer value, not a reference.

 inline int bump(const int & m) {    // return integer
  return m + 1;
 }

References to Pointers

References may also refer to pointers. The format is

 Type *& name = { init_list };      // reference to pointer 

The brace-enclosed init_list is optional and must contain a pointer expression whose type matches or converts to Type *. When you initialize references to pointers, the braces surrounding init_list are not necessary. Here's an example.

 double d = 3.4;           // d is a double
 double *pd = &d;           // pd is a pointer to a double
 double *& rpd = pd;         // rpd is a reference to a pointer to a double

Spaces are optional between the * and & operators, and arrays of references to pointers are illegal.

Why use references to pointers? Suppose, for example, you want to call a function that exchanges two integer pointers in memory. The following program accomplishes this with a pointer approach using double indirection (**).

Listing 3.9 Exchange pointers, using pointers

 // pxchg1.C - exchange pointers to integers in place using pointers
 #include <iostream.h>

 int main()
 {
  int a = 43, b = 56;
  int *pa = &a, *pb = &b;

  void pxchg(int **, int **);        // double indirect pointers

  cout << *pa << ' ' << *pb << endl;
  pxchg(&pa, &pb);             // pass pointers to pointers
  cout << *pa << ' ' << *pb << endl;
  return 0;
 }

 void pxchg(int **p, int **q) {        // double indirect pointers
  int *pt = *p;               // exchange pointers
  *p = *q;
  *q = pt;
 }

 $ pxchg1
 43 56
 56 43

We pass the addresses of the pointers to pxchg() so the function can swap them in memory. Inside pxchg(), we must be careful to apply single indirection (*) to exchange the pointers.

Here's the approach with references to pointers.

Listing 3.10 Exchange pointers, using references

 // pxchg2.C - exchange pointers to integers in place using references
 #include <iostream.h>

 int main()
 {
  int a = 43, b = 56;
  int *pa = &a, *pb = &b;

  void pxchg(int *&, int *&);      // references to pointers

  cout << *pa << ' ' << *pb << endl;
  pxchg(pa, pb);
  cout << *pa << ' ' << *pb << endl;
  return 0;
 }

 void pxchg(int *& p, int *& q) {     // references to pointers
  int *pt = p;              // exchange pointers
  p = q;
  q = pt;
 }

 $ pxchg2
 43 56
 56 43

The function prototype for pxchg() includes references to integer pointers, so we don't need the address operator (&) with arguments to invoke pxchg(). Similarly, we don't need pointer notation for the function arguments inside pxchg(). As an exercise, try removing the references (&) from this program (but retain each *). You'll discover the program compiles and runs but does not exchange pointers! (Can you explain why not?)

NOTE

Use references to pointers with function arguments instead of pointers to pointers. This approach eliminates pointer notation, simplifies the code, and makes it easier to follow.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020