C++ preprocessor __VA_ARGS__ number of arguments
#include <stdio.h> #include <string.h> #include <stdarg.h> #define NUMARGS(...) (sizeof((int[]){__VA_ARGS__})/sizeof(int)) #define SUM(...) (sum(NUMARGS(__VA_ARGS__), __VA_ARGS__)) void sum( int numargs, ... ); int main( int argc, char *argv[ ] ) { SUM( 1 ); SUM( 1, 2 ); SUM( 1, 2, 3 ); SUM( 1, 2, 3, 4 ); return 1; } void sum( int numargs, ... ) { int total = 0; va_list ap; printf( "sum() called with %d params:", numargs ); va_start( ap, numargs ); while ( numargs-- ) { total += va_arg(ap, int); } va_end( ap ); printf( " %d\n", total ); return; }
It is completely valid C99 code. It has one drawback, though - you cannot invoke the macro SUM()
without params,
but GCC has a solution to it - http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
So in case of GCC you need to define macros like this and it will work even with empty parameter list
#define NUMARGS(...) (sizeof((int[]){0, ##__VA_ARGS__})/sizeof(int)-1) #define SUM(...) sum(NUMARGS(__VA_ARGS__), ##__VA_ARGS__)
use this GNU extension, Just remember - it only works with GNU compiler.
#define macro(format, arguments...) fprintf(stderr, format, ##arguments)
The ##
token in combination with __VA_ARGS__
is a gcc extension that's not part of ISO C99.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本