c - 下面的 va_arg 宏是如何工作的?

标签 c macros c-preprocessor comma-operator

我正在阅读一个 stdarg.h(下面的链接)头文件,它定义了 va_arg 宏,如下所示

/*
 * Increment ap to the next argument in the list while returing a
 * pointer to what ap pointed to first, which is of type t.
 *
 * We cast to void* and then to t* because this avoids a warning about
 * increasing the alignment requirement.
 */
#define va_arg(ap, t)                   \
 (((ap) = (ap) + __va_argsiz(t)),       \
  *((t*) (void*) ((ap) - __va_argsiz(t))))

线

((ap) = (ap) + __va_argsiz(t))

重新分配 ap 的值,但我不明白逗号或行的用途

*((t*) (void*) ((ap) - __va_argsiz(t)))

Link to stdarg.h file

最佳答案

我们需要向调用者返回ap 指向的内容,提前ap。一个等价物是

    old_ap = ap
    ap = ap + argsiz
    return *old_ap

但是,这将需要一个额外的变量,这很难(如果可能的话)以可移植的方式在宏中处理。相反,宏依赖于逗号表达式。它推进 ap,然后计算其旧值,该值成为逗号表达式的值,即整个宏的值。

关于c - 下面的 va_arg 宏是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57629869/

相关文章:

macros - 从另一个命名空间调用的宏生成宏::无法引用不存在的合格变量

ios - 随机化预定义的数字

在编译时更改预处理值

c - 监控 CPU 温度增量 T 内核模块

c - K&R :C - Stack smashing detected

c - Ubuntu,POSIX mq_receive 在应该的时候没有阻塞

c++ - 有效和无效的pp token 的定义是什么?

c - gtk 初学者应用程序无法在断言失败的情况下工作

c++ - 用宏确定GCC编译器

c - C中栈变量的自动释放