Can "return" in C++ provide more than one variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can "return" in C++ provide more than one variable?

I'm wondering how write a function that returns more than one variable. For example, if a function is calculating a value using a while loop; I want the output to be the value and the number of loops iterated. I thought of defining an array or using a pointer is that the recommend methodology? Or "return" can return more than one value?

5th Oct 2017, 8:04 PM
Aider Matarrita
Aider Matarrita - avatar
3 Answers
+ 2
You can return multiple generic variables using tuple. Example: https://code.sololearn.com/c6VGn4sYxigL/#cpp The less generic solution would be to make a struct or class with all the variables you want to return in it, then you simply return an object of that class or struct.
5th Oct 2017, 8:30 PM
aklex
aklex - avatar
+ 1
You can't return more than one variable with the return keyword.. You'll have to pass by reference to the variables and add as many variables as you have results to return.
5th Oct 2017, 8:08 PM
Drax
Drax - avatar
0
thanks for all of your answers, I recently started with C++, I haven't even finish the training. So I was wondering about the extend of "return". Thanks for the examples, commands and mentioning the libraries required.
6th Oct 2017, 1:22 AM
Aider Matarrita
Aider Matarrita - avatar