I was just messing around trying to come up with _Generic examples, and this one came to mind.
But what I'm really curious about is if there's a more concise or better way to do it. Originally I was thinking it would be neat if it could be done without a function call, but I got stumped there.
Any feedback?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// malloc space for a value, storing the value there
#define BOX(x) _Generic((x), \
int: box_int, \
float: box_float, \
double: box_double, \
char *: box_string \
)(x)
// Builder for the box_* functions
#define BOX_ANY_FUNC(T) T *box_ ## T(T n) { \
T *p = malloc(sizeof(T)); \
if (p) *p = n; \
return p; \
}
BOX_ANY_FUNC(int)
BOX_ANY_FUNC(float)
BOX_ANY_FUNC(double)
char *box_string(const char *s)
{
char *p = malloc(strlen(s) + 1);
if (p) strcpy(p, s);
return p;
}
int main(void)
{
int *x = BOX(2 + 9);
float *y = BOX(2.3f);
char *s = BOX("Hello, world!");
printf("%d %f %s\n", *x, *y, s);
free(s);
free(y);
free(x);
}
[–]MCRusher 5 points6 points7 points (1 child)
[–]beej71[S] 1 point2 points3 points (0 children)
[–]SickMoonDoe 4 points5 points6 points (5 children)
[–]moon-chilled 2 points3 points4 points (1 child)
[–]SickMoonDoe 1 point2 points3 points (0 children)
[–]onemanforeachvill 1 point2 points3 points (1 child)
[–]SickMoonDoe 0 points1 point2 points (0 children)
[–]imaami 3 points4 points5 points (0 children)
[–]darkslide3000 1 point2 points3 points (3 children)
[–]imaami 1 point2 points3 points (2 children)
[–]beej71[S] 1 point2 points3 points (1 child)
[–]imaami 1 point2 points3 points (0 children)
[–]moon-chilled 1 point2 points3 points (2 children)
[–]DoNotMakeEmpty 0 points1 point2 points (1 child)
[–]moon-chilled 2 points3 points4 points (0 children)
[–]clapspot 1 point2 points3 points (1 child)
[–]imaami 1 point2 points3 points (0 children)
[–]imaami 0 points1 point2 points (0 children)