0

Let's assume I want to create a function first that returns the first element of an array in C. Obviously I want to create something that accounts for all types.

I would start with this:

int first(int list[]) {
   return list[0];
}

Which works. Obviously...

I would now like to do the same for char

char first(char list[]) {
   return list[0];
}

Which does not compile as there is already a first function in the program.

How do you C guys handle this kind of scenarios?

Is one forced to go with different names?

int first_int(int list[]) {
   return list[0];
}

char first_char(char list[]) {
   return list[0];
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
nourdine
  • 7,407
  • 10
  • 46
  • 58
  • You can't do that in C. It doesn't do this I'm afraid. You have to declare separate functions. – Baldrick Oct 19 '16 at 08:31
  • You might be able to get away with `_Generic` in C11, though I haven't tried it for an array. –  Oct 19 '16 at 08:35

1 Answers1

3

C11 introduced generic selections to emulate overloading:

#define first(X)          \
    _Generic((X),         \
        int* : first_int, \
        char*: first_char \
    )(X)

See it live on Coliru

Quentin
  • 62,093
  • 7
  • 131
  • 191