Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct return type for C function which returns different data types

Tags:

c

I was once asked to write a function which will return a pointer to some data in the memory upon some successful condition else it should return "-1". In this case, what would be the correct return type. If I only had to return the data then I would have char * as the return type of the function myfunction. But in this case, I may return -1 has return type.

<what-type> myfunction() {

char *data;

if (some condition true)
  return data;
else 
  return -1
}

int main () {

 myfunction

}
like image 659
modest Avatar asked Jan 14 '23 07:01

modest


1 Answers

Use union and perhaps define a typedef for it.

i.e.

typedef struct {
   int is_error;
   union {
     int error_code;
     char *data;
   }
} ReturnType;

Then

ReturnType myFunction(....) { ... etc }

The caller can check if the function is error (get a return error code) or get the data otherwise.

like image 133
Ed Heal Avatar answered Jan 17 '23 13:01

Ed Heal