Generic Programming C: Difference between revisions

From RidgeRun Developer Wiki
(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...")
 
No edit summary
Line 1: Line 1:
=Introduction=
=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.
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 [https://learn.microsoft.com/en-us/cpp/extensions/generics-and-templates-visual-cpp?view=msvc-170 link].


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

Revision as of 17:11, 26 May 2023

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