Last active
May 3, 2016 10:52
-
-
Save rockdaboot/dfd20c48697bb8c7201b9463b3082660 to your computer and use it in GitHub Desktop.
Iterate through array to make calculations using function pointers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#define N_ELEMENTS(array) (sizeof(array)/sizeof(*array)) | |
#define APPLY_FORMULA(result, array, func)\ | |
if (N_ELEMENTS(array)) {\ | |
result = array[0];\ | |
for (int8_t i = 1; i < N_ELEMENTS(array); i++)\ | |
result = func(result, array[i]);\ | |
} else\ | |
result = 0; | |
typedef uint16_t (*Formula_type)(uint16_t last, uint8_t nextItem); | |
static uint16_t add(uint16_t last, uint8_t nextItem) | |
{ | |
return last + nextItem; | |
} | |
static uint16_t mul(uint16_t last, uint8_t nextItem) | |
{ | |
return last * nextItem; | |
} | |
int main(void) | |
{ | |
uint8_t items[] = { 1, 2, 3, 4 }; | |
uint16_t total_add; | |
uint16_t total_mul; | |
APPLY_FORMULA(total_add, items, add); | |
APPLY_FORMULA(total_mul, items, mul); | |
printf("Total from adding = %d\n" | |
"Total from multiplying = %d\n", total_add, total_mul); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment