Advertisement
aaaaaa123456789

C optimization example - 100

Feb 15th, 2019
185
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. static void fold (const void * array, unsigned size, unsigned count,
  2.                   void (* callback) (void *, const void *), void * initial) {
  3.   const char * p = array;
  4.   while (count --) {
  5.     callback(initial, p);
  6.     p += size;
  7.   }
  8. }
  9.  
  10. static void add_integers (void * accumulator, const void * value) {
  11.   *(unsigned *) accumulator += *(const unsigned *) value;
  12. }
  13.  
  14. static unsigned sum_array (const unsigned * array, unsigned count) {
  15.   unsigned result = 0;
  16.   fold(array, sizeof *array, count, &add_integers, &result);
  17.   return result;
  18. }
  19.  
  20. static void initialize_array (unsigned * array, unsigned count) {
  21.   unsigned p;
  22.   for (p = 0; p < count; p ++) array[p] = p;
  23. }
  24.  
  25. unsigned hundred (void) {
  26.   unsigned values[10];
  27.   initialize_array(values, sizeof values / sizeof *values);
  28.   unsigned p, sum = sum_array(values, sizeof values / sizeof *values);
  29.   for (p = 0; p < (sizeof values / sizeof *values); p ++) values[p] = 10 - p;
  30.   return sum + sum_array(values, sizeof values / sizeof *values);
  31. }
Advertisement
RAW Paste Data Copied
Advertisement