Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Ways of returning results from the div function


Here are one of my experiments with the div function:

// C++ In A Nutshell example, page 36. Three version of divide.
// div returns an object that aggregates the quotient and the remainder.

#include <iostream>
// #include <cstdlib>

struct ldiv_t{
  ldiv_t(int a, int b):quot(a), rem(b){};
  int quot;
  int rem;
};

const ldiv_t& div(int x, int y){
  return ldiv_t(x / y, x % y);     // Warning. Problematic.
}

void divide_1 (long num, long den, long& quo, long& rem){
  ldiv_t result = div(num, den);         // The struct is COPIED out of div
  quo = result.quot;                    
  rem = result.rem;
}

void divide_2 (long num, long den, long& quo, long& rem){
  const ldiv_t& result = div(num, den);  // The struct is NOT COPIED out of div.
  quo = result.quot;                     // Instead a const reference is established 
  rem = result.rem;                      // to the resulting struct.
}

int main(){
  using namespace std;

  long  q, r;

  divide_1(107, 20, q, r);
  cout << q << " remainder " << r << endl;  // 5 remainder 7

  divide_2(107, 20, q, r);
  cout << q << " remainder " << r << endl;  // 5 remainder 7
}