Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using preprocessor directives to define generic functions in C

I just came to C from C# and was looking for a way to define generic functions like those in C#. I came across this post but when I tried to compile it I get a bunch of errors ("`n' undeclared here (not in a function)", " syntax error before "array" ", etc.) Here's my code:

#include<conio.h>
#include<stdlib.h>

#define MAKE_PRINTEACH(TYPE)\
void printeach_##TYPE (TYPE[n] array, int n, void(*f)(TYPE)){\
  int i;\
  for(i = 0; i < n; i++) {\
    f(array[i]);\
  }\
}

MAKE_PRINTEACH(int)
MAKE_PRINTEACH(float)

void printInt(int x)
{
     printf("got %d\n",x);
}

void printFloat(float x)
{
     printf("got %f\n",x);
}

int main()
{
    int[5] ia = {34,61,3,6,76};
    float[6] fa = {2.4,0.5,55.2,22.0,6.76,3.14159265};

    printeach_int(ia, 5, printInt);
    printeach_float(fa,6,printFloat);

    getch();
}

What am I doing wrong here? I am using DevC++ if that makes a difference.

like image 901
Zak Gambrell Avatar asked Oct 16 '25 15:10

Zak Gambrell


1 Answers

A correct version would look like this

#define MAKE_PRINTEACH(TYPE)                                     \
void printeach_##TYPE (size_t n, TYPE array[n], void(*f)(TYPE)){ \
  for(size_t i = 0; i < n; i++) {                                \
    f(array[i]);                                                 \
  }                                                              \
}

to summarize what went wrong with your version:

  • n must be declared before it is used
  • the array bounds come after the identifier
  • the semantically correct type for array sizes and things like that is size_t
  • C since C99 also has local variables for for loops.
like image 117
Jens Gustedt Avatar answered Oct 18 '25 08:10

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!