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

C++ Tutorial - Learn to use References

By David Bolton, About.com

3 of 7

Returning Reference Values from Functions

This has a function returning a reference value.
// 8_3.cpp
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int random(int max) {
return ( rand() % max)+ 1;
}

void randomize() {
srand( (unsigned)time( NULL ) ) ;
}

const maxemployees=100;
struct payrolltype {
int employeeid;
int salary;
bool employed;
std::string employeename;
payrolltype (int id,bool e,std::string s) :
employeeid(id), employed(e), employeename(s){} ;
payrolltype () : employeeid(0), employed( false), employeename("Person "), salary(0) {} ;
} ;

payrolltype payroll[maxemployees];

void sacksomeone(payrolltype & payroll ){
payroll.employed = false;
payroll.employeename="";
payroll.salary =0;
}
payrolltype & findhighestpaid() {
int highestsalary=0;
int highestindex=-1;
for (int i=0;i < maxemployees; i++) {
if (payroll[ i ].salary > highestsalary)
{
highestsalary = payroll[ i ].salary;
highestindex = i;
}
}
return payroll[ highestindex ];
}

int main(int argc, char* argv[]) {
randomize() ;
char buffer[50];
for (int i=0;i < maxemployees;i++) {
itoa(i+1,buffer,10) ;
std::string temp=buffer;
payroll[ i ].employeeid=i+1;
payroll[ i ].employed=true;
payroll[ i ].employeename += temp;
payroll[ i ].salary = (random( 100) + 30)*1000;
}
payrolltype highest = findhighestpaid() ;
cout << "Highest salary was " << highest.salary << std::endl;
sacksomeone( highest ) ;
return 0;
}
On the next page : How this example works.
Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Returning Reference Values from Functions

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

All rights reserved.