c - 为什么一些库例程同时实现为宏?为什么 "va_arg"宏被声明为函数(没有 "#define")?

标签 c function macros variadic-functions

我很难用语言清楚地表达出来。所以让我把它分成几部分。上下文来自 Mike Banahan 的 C 书籍(下面每个部分都提供了链接)。以下是我的问题,以粗体显示:

  • 为什么有些库函数也同时实现为宏?需要什么?这是我从书中读到的内容(Section 9.1.1) :

A last general point is that many of the library routines may be implemented as macros, provided that there will be no problems to do with side-effects (as Chapter 7 describes). The Standard guarantees that, if a function is normally implemented as a macro, there will also be a true function provided to do the same job. To use the real function, either undefine the macro name with #undef, or enclose its name in parentheses, which ensures that it won't be treated as a macro:

  • va_start,正如我们所知,是函数还是宏?书中的以下文字是困惑的根源,因为它在同一呼吸中,在相邻的行中暗示了两者! (Section 9.9)

Before any attempt can be made to access a variable argument list, va_start must be called. It is defined as

 #include <stdarg.h>
void va_start(va_list ap, parmN); 

The va_start macro initializes ap for subsequent use by the functions va_arg and va_end.

  • 最后是最令人困惑的部分。在下面的行中,清楚地写着va_arg是一个宏,并继续展示它是如何实现的。但是,如何在没有 #define 关键字的情况下实现宏,并且也像函数一样具有返回类型('type')呢? (Section 9.9)

Once initialized, the arguments supplied can be accessed sequentially by means of the va_arg macro. This is peculiar because the type returned is determined by an argument to the macro. Note that this is impossible to implement as a true function, only as a macro. It is defined as

#include <stdarg.h>
type va_arg(va_list ap, type);

我们将非常感谢您的回答。谢谢。

最佳答案

这是两个不同的问题。

首先,va_startva_argva_end保证是宏。 va_arg 不能是函数,因为它的第二个参数是类型而不是值。

至于为什么有些函数也是宏:因为您希望内联调用,使其更快,但您可能还想获取其地址并将其放入函数指针中:

int (*function_pointer)(int, FILE *) = &(putc);

关于c - 为什么一些库例程同时实现为宏?为什么 "va_arg"宏被声明为函数(没有 "#define")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26164849/

相关文章:

计算数组的一部分的平均值

c - 是否使用未初始化的值调用 `wait` 未定义行为?

c++ - 是否为函数调用中作为实际参数给出的字符数组分配了内存?

javascript - 使用函数更新表单值。 { react ,与 Formik}

javascript - javascript中的私有(private)变量意味着

c++ - 内联函数的具体用途是什么?

c - 为什么我们不应该在 C 中包含源文件

c - 在 C 中获取 'atoi' 函数的警告

c++ - 用 define 替换两次函数调用

c - 如何使用可变参数宏附加到数组?