Can a function return any type of result?

Hi everybody
I have a question for you. Can a function return any type of result? What I mean is if it can return an integer, or a char, or a boolean, depending of a requested value. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
void myfunction(int function_type) {
    switch(function_type) {
        case 0:
              return 14;
        break;
        case 1:
             return 'a';
        break;
        case 2:
             return false;
        break;
    }
}


So, this function would return (if possible) a different type of value, depending on its argument. How can this be done (if it is possible)? Thanks
Firstly, your function is defined as void, which means you aren't returning any value... Secondly, suppose you manage to do this, how will you use the function? You never know what value it'll return, so you can't really do much with it... What exactly do you want to achieve by managing to do this...? Just curious...
Everything has to have a type so it's not possible like that. A void* can point to any type but you still need to keep track of what type it is for to be useful, and with pointers you also have to clean up memory and all that. If the list of types is limited you can use a union.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
union T
{
    int i;
    char c;
    bool b;
};

T myfunction(int function_type) {
    T t;
    switch(function_type) {
    case 0:
        t.i = 14;
        break;
    case 1:
        t.c = 'a';
        break;
    case 2:
        t.b = false;
        break;
    }
    return t;
}

With this approach the caller still need to know what type he should read. You could put the union inside a struct and have variable tell you what type it is but all this becomes very complicated. You can probably solve it better in some other way by not returning different types.
Last edited on
Well, I have a file where some settings for my application are stored. The structure of a setting is settingname::settingtype::settingvalue.
I want to create a function that extracts the data from the settings file and depending of settingtype converts the settingvalue (which in the file is stored as char array) and returns it as the new converted value (which could be an integer, char array or boolean). Of course, it only can return the same type of value as the function type.
In languages like VB.NET you can create a void function that returns a value of any type. I wonder if C++ make this possible too.
OK, I see this is not recommended, the application could become unstable. I'll find another way. Thanks, anyway
Can't you store the setting values as strings and when you read it you explicitly request a specific type and if that fails you signal an error.
Last edited on
Topic archived. No new replies allowed.