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.

posted @   IAmAProgrammer  阅读(535)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 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搭建本
点击右上角即可分享
微信分享提示