Skip to content

Instantly share code, notes, and snippets.

@williamcotton
Last active March 9, 2025 12:13
Show Gist options
  • Save williamcotton/a8f429e891cbba5abfadcc0a929dda00 to your computer and use it in GitHub Desktop.
Save williamcotton/a8f429e891cbba5abfadcc0a929dda00 to your computer and use it in GitHub Desktop.
Use of generics in C11
#include <stdio.h>
#include <math.h>
// Define structures for different shapes
typedef struct Rectangle {
double width;
double height;
} Rectangle;
typedef struct Circle {
double radius;
} Circle;
// Generic area function using C11 generics
#define area(shape) _Generic((shape), \
Rectangle: area_rectangle, \
Circle: area_circle \
)(shape)
// Specific area implementations
double area_rectangle(Rectangle rect) {
return rect.width * rect.height;
}
double area_circle(Circle circle) {
return M_PI * circle.radius * circle.radius;
}
int main() {
Rectangle rect = {5.0, 3.0};
Circle circle = {2.5};
// Use the generic area function with different shapes
printf("Rectangle area: %.2f\n", area(rect));
printf("Circle area: %.2f\n", area(circle));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment