Advertisement
Guest User

X Macroing Arrays By Value

a guest
Apr 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.47 KB | None | 0 0
  1. #include "stdio.h"
  2.  
  3. #define STRUCT_NAME( type, count ) arr_##type##_##count##_s
  4. #define TYPE_NAME( type, count ) arr_##type##_##count##_t
  5. #define SUM_NAME( type, count ) sum_##type##_##count
  6. #define SUM( type, count, arg ) SUM_NAME( type, count )( arg )
  7.  
  8. #define X_TYPES     \
  9.     X( int, 1 )     \
  10.     X( int, 2 )     \
  11.     X( int, 3 )     \
  12.     X( double, 4 )
  13.  
  14. #define X( type, count ) \
  15.     typedef struct STRUCT_NAME( type, count )   \
  16.     {                                           \
  17.         type arr[count];                        \
  18.     } TYPE_NAME( type, count );
  19.  
  20. X_TYPES
  21.  
  22. #undef X
  23.  
  24. #define X( type, count ) \
  25.     type SUM_NAME( type, count )( TYPE_NAME( type, count ) val )    \
  26.     {                                                               \
  27.         int sum = 0, i;                                             \
  28.         for ( i = 0; i < count; i++ )                               \
  29.         {                                                           \
  30.             sum += val.arr[i];                                      \
  31.         }                                                           \
  32.         return sum;                                                 \
  33.     }
  34.  
  35. X_TYPES
  36.  
  37. #undef X
  38.  
  39. int main( int argc, char** argv )
  40. {
  41.     TYPE_NAME( int, 3 ) x = { { 1, 2, 3 } };
  42.  
  43.     printf( "%i\n", SUM( int, 3, x ) );
  44.  
  45.     TYPE_NAME( double, 4 ) y = { { 1.0, 2.5, 3.0, 4.5 } };
  46.  
  47.     printf( "%lf\n", SUM( double, 4, y ) );
  48.    
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement