Sandeep Singh
Sandeep Singh

Reputation: 5191

Return Different Data Types in C Function

I am having the following situation:

void func ()
{
    TEST_MACRO(....., ret_type)
    ..........
}

some_ptr* func2()
{
    TEST_MACRO(....., ret_type)
    ..........
}

int func3()
{
    TEST_MACRO(....., ret_type)
    ..........
}

I am having 3 types of functions. In each function, I have to do a range check for the same variable (local variable).

Depending upon the SUCCESS/FAILURE, I have to do the error handling in the Macro:

TEST_MACRO()
{
 // FAILURE
 if (ret_val == VOID_TYPE)
 {
    return;
 }
 else if (ret_val == RET_PTR)
 {
    return NULL;
 }
 else /* ret_val = INT */
 {
    return FAILURE;
 }
}

but ultimately, all the preprocessor code will land up into the same function.

Problem:

int func3 ()
{
  // Entire Error Handling
  if (..)
    return;
  else if(..)
    return NULL;
  else
    return FAILURE;
}

This is NOT possible, but to implement the SAME FUNCTIONALITY, i.e. doing a range check on the SIMILAR local variable, using 3 different Macros (one for each return type) doesn't seem to be a clean way.

Can somebody suggest me some good way of handling such a situation?

Upvotes: 1

Views: 1680

Answers (1)

Dave
Dave

Reputation: 11162

Flow-control macros notoriously evil. Instead make your macro yield a boolean value, and respond to that within your function. It's much clearer this way:

void func ()
{
    if(!TEST_MACRO(.....))
         return;
    .......... 
} 

int func ()
{
    if(!TEST_MACRO(.....))
         return FAILURE;
    .......... 
} 

Upvotes: 2

Related Questions