Search code examples
cfunctionstructreturn-type

Is there any way to keep the return type of a function variable?


I want to define a function, that returns either a struct with multiple values of variant type or a single int * depending on arguments, a user passes over the command line.
I know, that I could just simply always return a struct and retrieve the specific values from the struct related to users input data, but I was wondering if there is any possibility to state that a function will return either A or B.


Solution

  • Probably the closest approach would be to return a union of structs with additional type info.

    typedef struct {
       MyType type;
       int    alpha;
       float  beta;
       char * gamma;
    } A;
    
    typedef struct {
       MyType type;
       int *  data;
    } B;
    
    typedef union {
      MyType type;
      A a;
      B b;
    } Returnable;
    
    // Returnable func (void);
    

    However, you need to either check args before function call or type field after. In the latter case you lose compiletime type checking and invent runtime type checking, which can be error-prone.


    As @EricPostpischil suggested in comments, one more approach:

    typedef struct {
      int foo;
    } A;
    
    typedef struct {
      char bar;
    } B;
    
    typedef struct {
      MyType data_type;
    
      union {
        A a;
        B b;
      } data;
    } Returnable2;