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 thisand 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.
原文链接: https://www.cnblogs.com/shangdawei/archive/2013/05/28/3102927.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/90343

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午12:35
下一篇 2023年2月10日 上午12:36

相关推荐