Generic Programming C

From RidgeRun Developer Wiki
Revision as of 16:35, 26 May 2023 by Anavarro (talk | contribs) (Created page with "=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 cla...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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 https://learn.microsoft.com/en-us/cpp/extensions/generics-and-templates-visual-cpp?view=msvc-170.

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