Return type in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Return type in C++

Is there any way that a function will return two different data types by different conditions.. like if condition is true it will return an integer value and if it goes false it will return a string like "not found"

17th Jun 2018, 9:31 AM
Fuad Hasan
Fuad Hasan - avatar
4 Answers
+ 4
Fuad Hasan A function is a machine capable of accepting zero or more inputs and delivering one output at most (That's what it is!). But no give up! The two primitive ways to work around this limitation (if you wanna stick with function anyhow) are, 1. Passing those two variables from main for example, to function f via reference or pointer and then modifying them there (pipelining return values, in my term!) 2. Developing a compound data type which consists of two variables by wrapping them in a class/struct. Then, using that as function f's return type as simple as you do it with built-in types. Let me make it clear for you by two examples // First approach void f(int &n, double &d) { // Under certain condition, f will change (yield) n as one of the two variables (returns). if (n == 0) n++; // tied to var1 d *= 2; // tied to var2 } int main() { // These two guys are defined to act like return types. int var1 = 0; double var2 = 2.0; cout << var1 << "\t" << var2 << "\n"; // 0 2 f(var1, var2); cout << var1 << "\t" << var2 << "\n"; // 1 4 } // Second one struct custom_t { int var1; double var2; }; custom_t f() { custom_t temp; temp.var1 = 0; temp.var2 = 2.0; if ( temp.var1 == 0) temp.var1++; temp.var2 *= 2; return temp; } int main() { custom_t ct = f(); cout << ct.var1 << "\t" << ct.var2; // 1 4 } Fortunately, C++11 offers some better solutions to the cause.
17th Jun 2018, 12:07 PM
Babak
Babak - avatar
0
look into std::optional or std::tuple
17th Jun 2018, 9:55 AM
Max
Max - avatar
0
std::optional is the solution that I wanted that time. Max thanks for your answer. Replying 2 years later. 😂 Learnt a lot in these times.
26th Oct 2020, 6:12 AM
Fuad Hasan
Fuad Hasan - avatar
- 1
No... You can return an object that contain either but in your case its not a good solution. A better (and usually used) solution its use an integer that mean not found: int check(int p){ if(p>10) return 10; // here -1 say to callee // that condition its not // satisfed return -1; }
17th Jun 2018, 9:39 AM
KrOW
KrOW - avatar