Can a Function return different types depending on conditions?

I want to write a function that that performs a calculation if the parameters passed to it are in a certain range, but returns the word "ERROR" if they are not in range. That requires a function that sometimes returns a double, and sometimes returns a string. This doesn't appear to be possible. Templates seem to allow you to send different data types, but not return multiple data types. Anyone have an idea on how to do what I'm looking for in a function?

Thanks!
You can't return different data types like you are suggesting. You could create some kind of new type that contains the data you want to return and a boolean value that determines whether the actual data value is good, like (very simply):
1
2
3
4
struct ret_val {
   int ret_data; // only check this if no error
   bool is_good; // use this to return an error
};

There are better ways to implement the idea but you get the idea.
A function cannot return a double and a string. The closest you can get is to return a struct containing a double and a string.

This looks like a job for exceptions:
http://cplusplus.com/doc/tutorial/exceptions/

I suppose another alternative would be to pass the double by reference and have the method return a string. Based on the value of the returned string you could decide whether or not to use the double. However, this is a hideous contract to make with the rest of your program. It is convoluted and confusing to potential users.

EDIT: A little more in-depth linkie goodness: http://www.parashift.com/c++-faq/exceptions.html
Last edited on
The problem is that how will the calling code get the return value?:)
You have several approaches. For example you can return std::pair<double, bool>. So the calling code will can check the second member for true of false.
The other approach is to return some values through patameters declared as references.
You can only do that in a full OOP language where every data type is derived from a base object.
Topic archived. No new replies allowed.