0

is it possible to return multiple values from a function ?

if yes then how ?

21st Aug 2016, 3:46 PM
priyanshu chakarvarti
priyanshu chakarvarti - avatar
4 Answers
+ 2
If they are of the same data type, you can put those values in an array, and return that array. There is no way to return multiple values of different data types, so in that case you'll have to restructure you program.
21st Aug 2016, 4:30 PM
Jonathan Dirks
Jonathan Dirks - avatar
+ 2
@Mohit: You are right, one can do that. Nevertheless, there's a reason why using the reference approach is a bit out of fashion: it's hard to read and understand. It's perfectly common in C but C++11 and after have means to deal with some inefficiencies.
21st Aug 2016, 5:58 PM
Stefan
Stefan - avatar
+ 1
Yes, there are data structures that enable you to do this. std::pair or in C++11 and after std::tuple. Before that you could use boost::tuple from the external Boost library (one of the most commonly used libraries for C++). You could also write your own but why would you, if you have easy access to C++11 or Boost.
21st Aug 2016, 4:32 PM
Stefan
Stefan - avatar
+ 1
Instead of returning two or more values make the function accept parameters by reference by using &. Set return type of function to void. Alter the values of the parameter inside the function and they will also get altered in the actual variables inside main()
21st Aug 2016, 5:33 PM
Mohit Jain
Mohit Jain - avatar