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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With