Skip to content

Instantly share code, notes, and snippets.

@somdoron
Last active March 19, 2019 13:07
Show Gist options
  • Save somdoron/e6827558984600d36628c3cca3343c68 to your computer and use it in GitHub Desktop.
Save somdoron/e6827558984600d36628c3cca3343c68 to your computer and use it in GitHub Desktop.
match expression in c
void main() {
char* first =
match(char *, 1) {
when(1):
return "Drake";
when(2):
return "Charles";
otherwise:
return "";
end
}
char *last =
match (char *, first) {
when("Drake"):
return "Lucas";
otherwise:
return "Don't know";
end
}
printf("%s %s", first, last);
}
#ifndef __MATCH__
#define __MATCH__
#include <stdio.h>
#include <string.h>
#define match_concat(x,y) x##y
#define match(type,x) \
({ \
__auto_type value = x; \
int _eq(typeof (x) a, typeof (x) b) { \
return a == b; \
} \
int _streq(const char* a, const char* b) { \
return strcmp (a,b) == 0; \
} \
type _match(typeof (x) value) { \
if (0)
#define _when(x, idx) \
} \
if (_Generic(x, char *: _streq, const char *: _streq, default: _eq)(value,x)) { \
goto match_concat(match_label_, idx); \
} \
if (0) { \
match_concat(match_label_, idx)
#define _otherwise(idx) \
} \
goto match_concat(match_label_, idex); \
if (0) { \
match_concat(match_label_, idex)
#define end \
} \
} \
_match(value); \
}); {
#define when(x) _when(x, __COUNTER__)
#define otherwise _otherwise(__COUNTER__)
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment