| references/ref-fields.cc - Convenient references to long/deep fields. | Lecture 2 - slide 15 : 29 Program 7  | 
// Illustrates how a reference can be used for naming convenience.
// A program with two versions of the function work_on_persons_road_number.
#include <iostream>
#include <string>
using namespace std;
typedef struct{
  char road[15];
  int roadNumber;
  char town[20];
  } address;   
typedef struct{
  int idNumber;
  char firstName[10],
       lastName[20];
  address location;} person;   
bool even(int n){
  return n%2 == 0;
}
// A function in which a long and deep field name is used many times.
void work_on_persons_road_number(person &p){
  if (even(p.location.roadNumber))
    p.location.roadNumber = p.location.roadNumber + 1;
  else
    p.location.roadNumber = 0;
}
// A version of the function that binds the roadNumber field to an
// int reference.
void work_on_persons_road_number_with_ref(person &p){
  int &lrn = p.location.roadNumber;
  if (even(lrn))
    lrn = lrn + 1;
  else
    lrn = 0;
}
void print_person(person &p){
  cout << p.firstName << " " << p.lastName << endl
       << p.location.road << " " << p.location.roadNumber << endl
       << p.location.town << endl << endl;
}
 
int main(){
  person morten = 
     {190583,                             /* Initializer      */
      "Morten", "Madsen",                 /* and only that... */
      {"Bredgade", 23, "Middelfart"}
     };
  print_person(morten);
  work_on_persons_road_number(morten);
  print_person(morten);
  work_on_persons_road_number_with_ref(morten);
  print_person(morten);
}