fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef enum {
  5. INT,
  6. STR,
  7. } type;
  8.  
  9. typedef struct {
  10. type type;
  11. union {
  12. char *s;
  13. int i;
  14. };
  15. } variant_t;
  16.  
  17. #define VARIANT(x) _Generic((x), \
  18. int: ((variant_t){.type = INT, .i = x}), \
  19. char*: ((variant_t){.type = STR, .s = x}) \
  20. )
  21.  
  22. void foo_int(int i)
  23. {
  24. printf("Integer %d\n", i);
  25. }
  26.  
  27. void foo_str(char *s)
  28. {
  29. printf("String \"%s\"\n", s);
  30. }
  31.  
  32. #define foo(x) (_Generic((x), \
  33. int: foo_int, \
  34. char*: foo_str \
  35. )(x))
  36.  
  37. void dynamic_foo(variant_t pitux)
  38. {
  39. switch (pitux.type) {
  40. case INT: foo(pitux.i); break;
  41. case STR: foo(pitux.s); break;
  42. default: error("Error!"); break;
  43. }
  44. }
  45.  
  46. int main(void)
  47. {
  48. for (int i = 0; i < 10; ++i) {
  49. dynamic_foo(rand() & 1 ? VARIANT(42): VARIANT("forty two"));
  50. }
  51. return 0;
  52. }
Success #stdin #stdout 0s 4284KB
stdin
Standard input is empty
stdout
Integer 42
String "forty two"
Integer 42
Integer 42
Integer 42
Integer 42
String "forty two"
String "forty two"
Integer 42
Integer 42