Home > Net >  How do I know whether my function returns a value in C
How do I know whether my function returns a value in C

Time:07-04

I wrote a macro which checks whether calloc success like

#define CHECK_CALLOC(ptr)                                             \
    if (ptr == NULL)                                                  \
    {                                                                 \
        printf("Error: failed to calloc in %s line %d of func %s.\n", \
               __FILE__, __LINE__, __FUNCTION__);                     \
        return;                                                       \
    }

However in some functions that returns a value, I have a warning with GCC saying "warning: 'return' with no value, in function returning non-void". So I'm wondering if there exists something like argc that tells me whether my function returns a value. Or can I know whether this function is a void (non-value-returning) function?

#define CHECK_CALLOC(ptr)                                             \
    if (ptr == NULL)                                                  \
    {                                                                 \
        printf("Error: failed to calloc in %s line %d of func %s.\n", \
               __FILE__, __LINE__, __FUNCTION__);                     \
        if (ifReturns)                                                \
            return NULL;                                              \
        else                                                          \
            return;
}

CodePudding user response:

You can use variable arguments to specify the return value to use if the function returns a value.

#define CHECK_CALLOC(ptr, ...)                                        \
    if (ptr == NULL)                                                  \
    {                                                                 \
        printf("Error: failed to calloc in %s line %d of func %s.\n", \
               __FILE__, __LINE__, __FUNCTION__);                     \
        return __VA_ARGS__;                                           \
    }

void foo()
{
    void *p = calloc(1,1);
    CHECK_CALLOC(p);
}

int bar()
{
    void *p = calloc(1,1);
    CHECK_CALLOC(p,0);
    return 1;
}

void *baz()
{
    void *p = calloc(1,1);
    CHECK_CALLOC(p,NULL);
    return p;
}
  •  Tags:  
  • c
  • Related