freonix
freonix

Reputation: 1625

Returning variable type

Is it possible to have a function or macro to return variable type? I need to implement something like a conditional typedef. Example:

    (var_type) foo (char a)
    {
        if (a == 1)
           return char;
        else 
           return int;    
     }

Such that I could :

foo(1) variable;

Note: The above is just a pseudo-code.

Upvotes: 2

Views: 179

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61519

This is fundamentally impossible: types in C need to be known at the time the code is written (that's why you have to write them at all in the first place), and the function cannot 'return' until it runs, which happens after the program has been compiled.

What are you really trying to do? Why do you need variable to be either a char or an int depending on something that happens at runtime? What Bad Thing(TM) happens if we just make it an int and then we never end up assigning it a value that wouldn't fit in a char? We waste 3 bytes on the stack? Oh dear.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612954

You can do this with a macro but only if the type can be determined at compile time. Otherwise you're out of luck.

Since you are trying to declare a variable it follows that foo must be known at compile time.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182639

You can't do that. You could allocate your object on the heap and return a void * to it. Or perhaps you could use a union.

Upvotes: 3

Related Questions