【问题标题】:Macro for printing variadic arguments, with the option of no arguments用于打印可变参数的宏,可以选择无参数
【发布时间】:2018-10-29 10:06:58
【问题描述】:

我想实现以下宏:

ASSERT(condition, ...)          

定义如下:
1. 如果它只有一个参数 - 如果条件为假,我们只打印“条件为假”。
2. 如果它有两个或更多参数 - 与上面相同,另外:第二个参数将是打印格式(类似于 printf 格式),其余参数将是打印格式(再次,就像 printf) .因此,除了可能打印“条件为假”之外,它还会像 printf 一样打印格式。

例子:

  1. 断言(0):

    condition is false 
    
  2. 断言(1):

    (empty output)
    
  3. 断言(0,“嗨”):

    condition is false
    hi
    
  4. ASSERT(0, "第七个: %d", 7) :

    condition is false
    number seven: 7
    

我的问题是我不知道如何支持零可变参数的情况。如果我知道我肯定会得到至少两个参数 - 我可以像下面的代码那样实现它,但事实并非如此。
如何修改下面的代码以支持我需要的内容?

#define ASSERT(condition, format,...) do { \
  if (!(condition)) { \
    printf(format, ##__VA_ARGS__); \
  } \
} while (0)

【问题讨论】:

标签: c macros c-preprocessor variadic variadic-macros


【解决方案1】:

您可以从该宏中删除format 参数(将它们拉入可变参数部分)。 "condition is false\n" 和格式字符串(如果存在)将连接成一个没有## 的字符串。

#include <stdio.h>

#define ASSERT(condition, ...) do { \
  if (!(condition)) { \
    printf("condition is false\n" __VA_ARGS__); \
  } \
} while (0)

int main()
{
    ASSERT(1);
    ASSERT(0);
    ASSERT(0,"Hi\n");
    ASSERT(0,"number is %d\n",7);
    return 0;
}

限制:

  • format 应该是 only 字符串文字,而不是指向字符数组的指针

【讨论】:

    猜你喜欢
    • 2014-05-22
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多