zoukankan      html  css  js  c++  java
  • 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.


  • 相关阅读:
    图像滤波与OpenCV中的图像平滑处理
    OpenCV创建轨迹条,图片像素的访问
    模板类和友元的总结和实例验证
    C++中运算符重载
    C++之Stack模板类
    C++中explicit关键字的作用
    #ifdef-#endif的作用及其使用技巧
    ZOJ 3170 Friends
    ZOJ 3713 In 7-bit
    HDU 1421 搬寝室
  • 原文地址:https://www.cnblogs.com/shangdawei/p/3102927.html
Copyright © 2011-2022 走看看