Main Content

How to return 2 values from a function (C++ and C) - more uses of pointers

Archive - Originally posted on "The Horse's Mouth" - 2011-04-10 11:37:54 - Graham Ellis

A further example (following previous article [here]) of where pointers are particularly useful is where you want to return nore than one resulting value from a function ... in C, that's something you couldn't really do without them.

There are two ways:

a) A function returns a single value ... but you can make that return value a pointer, so that you can reurn a whole array or structure of values and

b) You can pass in a pointer to your function, so that the value(s) at the address passed in and at subsequent memory addresses can be modified withn the function, thus forming a second return.

Let's see an example of where you might wish to do this, written as a practical demonstration on last week's run of our public C programming course.

I have £150.00 which I want to spend on the hire of a forklift truck for as long as possible. Hire costs £22.00 per month, £10.00 per week and £3.50 per day ... how long can I have the forklift truck for?

code:

  float bank = 150.00;
  int month, week, day;
  month = spend(&bank,22.00);
  week = spend(&bank,10.00);
  day = spend(&bank,3.50);


The spend function has two inputs - the amount that's available (your balance) and the cost of the forklift truck for one unit of time. It returns the number of complete time units. And it alters the balance in the "bank" variable - it's able to do so because it's the address that's been passed in.


Compelete source and sample output - [here]. The image that accompanies this article is public domain and we claim no copyright over it.