-1

Which one is better if I have to return a string as well as an array from a function.

  1. Create a structure containing string and array, populate that and return the instance of that structure.

Consider I have to send string "status" and an array "ids".

    struct ReturnValues {
      string status;
      int ids[10];
    }; 

use it as:

ReturnValues returnValues;
returnValues = func();

Consider that func() returns the object of ReturnValues

  1. Pass one of them as referenced variable and return the other.

As:

int ids[10];
string status = func(ids);

Consider that func takes ids as referenced variable

string func(int& ids) {
  //Some code
  return status;
}
  1. Pass both as referenced variables returning void.

As:

int ids[10];
string status;
func(ids, status);

Consider that func takes ids and status as referenced variables

void func(int& ids, string& status) {
  //some code;
}

3 Answers3

1

Strictly from a performance standpoint, it would give the compiler the most leverage to optimize if you do :

struct ReturnValues {
  string status;
  int ids[10];
}; 

and

ReturnValues returnValues = func();

Doing

ReturnValues returnValues;
returnValues = func();

will decrease performance since return-value optimization cannot take place : http://goo.gl/5Cfmw2

Jean-Michaël Celerier
  • 7,412
  • 3
  • 54
  • 75
  • Right, and the second version should also be avoided for other reasons: You cannot make returnValues const, somebody might try to access the uninitialized variable and finally it is more verbose. – Frank Puffer Feb 26 '16 at 12:40
0

I would definitely go for the 1st version. Functions that modify their arguments tend to make the code more difficult to understand and test.

If you are worried about performance: Practically all compilers will use return value optimization here. So this should not be an issue, maybe except in some exotic cases.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
0

Personally I would either group them together either into a predefined struct as you did or use std::pair or tuple if you don't want to define one explicitly. My feeling is that things that belong together belong together (if you'll forgive the tautology). Either way I would consider using std::array if the array length is fixed or std::vector (or some collection type) if not. Am not a fan of level C type arrays such astype A[10] I would probably just return them as a return value simply because it shows the intent "Get me one of these things with ints and strings in it" and let the compiler sort it out

systemcpro
  • 856
  • 1
  • 7
  • 15