#include <stdio.h>
#include <stdarg.h>
void say_hello( char* name )
{
printf( "hello %s\n" , name );
return;
}
//takes a named function, and calls it for each element in the array
//problems: must create function for every different way of calling this (pollutes namespace, dissassociates action from location)
// needs to know too much information about the array (ie it is char** so can't pass int** or double** )
// needs to know too much information about the function being called to handle it (ie it's return type, and type of params)
void for_each( char** array , int size , void (*action)( char* ) )
{
int i;
for( i=0 ; i<size ; ++i ) action(array[i]);
return;
}
//can take any type, can receive and execute code, also executes in local environment
//problems: name conflicts, in this case, the local variable i is likely to conflict with some other code somewhere
// so if they use i in their code, then they have a conflict
// ( my solution has been to obfuscate the variable name like this: i_akA90hv23 )
#define FOR_EACH( array , size , the_element , your_code ) \
{ \
int i; \
for( i=0 ; i<size ; ++i ) \
{ \
the_element = array[i]; \
your_code; \
} \
}
int main( int argc , char const *argv[] ) {
char *a[] = { "josh","gen","hoang" };
//using function pointers
for_each( a , 3 , say_hello );
printf( "\n\n\n" );
//same as the above, but macros make it feel like an anonymous function
char* name;
FOR_EACH( a , 3 , name ,
printf( "hello %s\n" , name );
)
printf( "\n\n\n" );
//using macros again, this shows that you can handle different types of arrays, and have local scope
int b[] = { 1 , 2 , 3 };
int the_int , sum=0;
FOR_EACH( b , 3 , the_int ,
sum += the_int;
printf( "the int is %d , sum is %d\n" , the_int , sum );
)
return 0;
}