有没有办法为 return 不同类型的值提供单个宏函数,包括什么都没有?

Is there a way to provide a single macro function to return values of different types including nothing?

我已经创建了以下宏来锁定互斥量和 return(从调用此宏的函数)以防锁定尝试失败。目前我已经将它缩小到 2 个宏 - 一个用于 returning 来自函数 return 一个值,无论类型如何,另一个用于 returning 来自 return 的函数] 什么都没有(即 void)。

宏之外的代码(下方)仅供参考,与将使用宏的实际生产代码关系不大。

#define MUTEX_LOCK()\
    {\
        if (pthread_mutex_lock(&mutex) != 0)\
        {\
            printf("Failed to lock mutex.\n");\
            return;\
        }\
    }
#define MUTEX_LOCK_RVAL(err_val)\
    {\
        if (pthread_mutex_lock(&mutex) != 0)\
        {\
            printf("Failed to lock mutex.\n");\
            return err_val;\
        }\
    }

void vfunc()
{
    printf("\nIn vfunc()\n");
    MUTEX_LOCK();
    printf("\nOut of vfunc()\n");
}

UINT16 uint16func()
{
    printf("\nIn uint16func()\n");
    MUTEX_LOCK_RVAL(0);
    printf("\nOut of uint16func()\n");

    return 9;
}

CHAR* errstr = "Hoo boy!";
CHAR* strfunc()
{
    printf("\nIn strfunc()\n");
    MUTEX_LOCK_RVAL(errstr);
    printf("\nOut of strfunc()\n");

    return NULL;
}

有没有办法将它们缩减为单个宏,可以在函数中使用 returning 值以及 void.

据我从文档中得知,您可以删除不带参数的宏函数,因为您根本没有义务将参数传递给需要参数的宏函数。
来自 GNU GCC documentation:

You can leave macro arguments empty; this is not an error to the preprocessor [...]


对于多个参数,这很有趣:

You cannot leave out arguments entirely; if a macro takes two arguments, there must be exactly one comma at the top level of its argument list.

给出这些例子:

min(, b)        ==> ((   ) < (b) ? (   ) : (b))
min(a, )        ==> ((a  ) < ( ) ? (a  ) : ( ))
min(,)          ==> ((   ) < ( ) ? (   ) : ( ))
min((,),)       ==> (((,)) < ( ) ? ((,)) : ( ))

我能想到的唯一解决方案是:

#define MUTEX_LOCK( err_val )\
{\
  {\
      if (pthread_mutex_lock(&mutex) != 0)\
      {\
          printf("Failed to lock mutex.\n");\
          return err_val;\
      }\
   }\
}

int test_int()
{
    MUTEX_LOCK( 1 );

    return 0;
}

void test_void()
{
    MUTEX_LOCK( ; );

    return;
}

为了使其与 ANSI 兼容,我用 return 和另一个求值为 null 的简单符号定义宏,并清楚地表明它为 null。 即:

#define VOID_RET    //This nulls the return value
#define MUTEX_LOCK(err_val)\
    {\
        if (pthread_mutex_lock(&mutex) != 0)\
        {\
            printf("Failed to lock mutex.\n");\
            return err_val;\
        }\
    }
void *mutex = NULL;
void vfunc(void)
{
    printf("\nIn vfunc()\n");
    MUTEX_LOCK(VOID_RET);
    printf("\nOut of vfunc()\n");
}
UINT16 uint16func(void)
{
    printf("\nIn uint16func()\n");
    MUTEX_LOCK(0);
    printf("\nOut of uint16func()\n");

    return 9;
}
CHAR* errstr = "Hoo boy!";
CHAR* strfunc(void)
{
    printf("\nIn strfunc()\n");
    MUTEX_LOCK(errstr);
    printf("\nOut of strfunc()\n");

    return NULL;
}

我在 C11 和 C99 下测试了这段代码。