开发者

Returning variable type

Is it possible to have a function or macro to return variable type? I need to impl开发者_如何学Pythonement 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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜