我很难用语言清楚地表达出来。所以让我把它分成几部分。上下文来自 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_start
、va_arg
和va_end
保证是宏。 va_arg
不能是函数,因为它的第二个参数是类型而不是值。
至于为什么有些函数也是宏:因为您希望内联调用,使其更快,但您可能还想获取其地址并将其放入函数指针中:
int (*function_pointer)(int, FILE *) = &(putc);
关于c - 为什么一些库例程同时实现为宏?为什么 "va_arg"宏被声明为函数(没有 "#define")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26164849/