Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why methods can not return multiple values

Just curious is there any technical limitation in having multiple return values for methods in languages like java, c, c++ or limitation is just by spec? In assembly language I understand callee can pop one value to register.

like image 964
Dileep Avatar asked Jun 23 '11 18:06

Dileep


2 Answers

  1. Because in the days of C there is/was a single register used to hold the return value.
  2. Because if you need more values, you can just return a struct, reference (in Java/C#), or pointer.
  3. Because you can use an out parameter.

Allowing multiple return values would add complexity, and it's simply worked around. There's no reason for it to be there. (Indeed, in C++ you can return a tuple (from TR1, C++11, or boost) which effectively is multiple return values)

like image 78
Billy ONeal Avatar answered Sep 27 '22 19:09

Billy ONeal


Its by design, because there is no need to allow multiple values in return statement. You can always define a struct with all the needed members, and create an instance of the struct and return it. Simple!

Example,

struct Person
{
   std::string Name;
   int Age;
   std::string Qualification;
   //...
};

Person GetInfo()
{
    Person person;
    //fill person's members ...
    return person;
}

You can use std::pair, std::vector, std::map, std::list and so on. In C++0x, you can use std::tuple as well.

like image 45
Nawaz Avatar answered Sep 27 '22 17:09

Nawaz