Generic Programming C
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
For direct inquiries, please refer to the contact information available on our Contact page. Alternatively, you may complete and submit the form provided at the same link. We will respond to your request at our earliest opportunity.
Links to RidgeRun Resources and RidgeRun Artificial Intelligence Solutions can be found in the footer below.