SHARE
TWEET

X Macroing Arrays By Value

a guest Apr 19th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  6. #define X_TYPES     \
  7.     X( int, 1 )     \
  8.     X( int, 2 )     \
  9.     X( int, 3 )     \
  10.     X( double, 4 )
  11.  
  12. #define X( type, count ) \
  13.     typedef struct STRUCT_NAME( type, count )   \
  14.     {                                           \
  15.         type arr[count];                        \
  16.     } TYPE_NAME( type, count );
  17.  
  18. X_TYPES
  19.  
  20. #undef X
  21.  
  22. #define X( type, count ) \
  23.     type sum_##type##_##count( TYPE_NAME( type, count ) val )   \
  24.     {                                                           \
  25.         int sum = 0, i;                                         \
  26.         for ( i = 0; i < count; i++ )                           \
  27.         {                                                       \
  28.             sum += val.arr[i];                                  \
  29.         }                                                       \
  30.         return sum;                                             \
  31.     }
  32.  
  33. X_TYPES
  34.  
  35. #undef X
  36.  
  37. int main( int argc, char** argv )
  38. {
  39.     TYPE_NAME( int, 3 ) x = { { 1, 2, 3 } };
  40.  
  41.     printf( "%i\n", sum_int_3( x ) );
  42.  
  43.     TYPE_NAME( double, 4 ) y = { { 1.0, 2.5, 3.0, 4.5 } };
  44.  
  45.     printf( "%lf\n", sum_double_4( y ) );
  46.    
  47.     return 0;
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top