Generic Programming C

From RidgeRun Developer Wiki
Revision as of 17:11, 26 May 2023 by Emurillo (talk | contribs)

Introduction

One of the coolest features of modern higher programming languages like C# or Java, is the concept of generic programming, in which you can have methods or classes that work for different types at runtime. C++ also offers a similar mechanism with the concept of templates, with the difference that they have to be resolved at compilation time, for more details see the following link.

But did you know you can also achieve something similar with C introduced in C11?

Here is an example

#include <stdio.h>

#define PRINT_GENERIC(v)  _Generic(v, char* : sprint, \
                            int : iprint, \
                            long : lprint)(v)

static inline void lprint(long v) {
  printf("lprint: %ldL\n", v);
}
static inline void iprint(int v) {
  printf("iprint: %d\n", v);
}

static inline void sprint(char* v) {
  printf("sprint: %s\n", v);
}
  
int main()
{
    PRINT_GENERIC(250L);
    PRINT_GENERIC(250);
    PRINT_GENERIC("Hi");
}

The output is

lprint: 250L
iprint: 250
sprint: Hi