Skip to content

Instantly share code, notes, and snippets.

@sug0
Created August 21, 2018 17:05
Show Gist options
  • Save sug0/ea6c1f524469aed7b5c1181691c2d699 to your computer and use it in GitHub Desktop.
Save sug0/ea6c1f524469aed7b5c1181691c2d699 to your computer and use it in GitHub Desktop.
Enhanced switch meta control structure in C
#include <stdio.h>
#include <string.h>
#include "metaswitch.h"
int intcmp(const void *x, const void *y)
{
return *(int *)x - *(int *)y;
}
int main(void)
{
puts("> switch");
switch_begin {
switch_case (1 == 2)
puts("1 == 2");
switch_break;
switch_case (2 == 2)
puts("2 == 2");
switch_fallthrough;
switch_case (3 == 3)
puts("3 == 3");
switch_fallthrough;
switch_default
puts("default");
switch_break;
} switch_end;
puts("> str switch");
switch_str_begin ("foo") {
switch_str_case ("no")
puts("no");
switch_str_break;
switch_str_case ("foo")
puts("foo");
switch_str_fallthrough;
switch_str_case ("bar")
puts("bar");
switch_str_break;
switch_str_default
puts("default");
switch_str_break;
} switch_str_end;
puts("> eq switch");
switch_eq_begin (int, 1) {
switch_eq_case (3)
puts("3");
switch_eq_break;
switch_eq_case (1)
puts("1");
switch_eq_fallthrough;
switch_eq_case (2)
puts("2");
switch_eq_break;
switch_eq_default
puts("default");
switch_eq_break;
} switch_eq_end;
puts("> cmp switch");
int x = 1, y = 2, z = 3;
switch_cmp_begin (intcmp, &x) {
switch_cmp_case (&y)
puts("z");
switch_cmp_break;
switch_cmp_case (&x)
puts("x");
switch_cmp_fallthrough;
switch_cmp_case (&z)
puts("z");
switch_cmp_break;
switch_cmp_default
puts("default");
switch_cmp_break;
} switch_cmp_end;
return 0;
}
#ifndef METASWITCH_H
#define METASWITCH_H
#define switch_begin do
#define switch_case(X) if (X) {
#define switch_break break; }
#define switch_fallthrough }
#define switch_default {
#define switch_end while (0)
#define switch_str_begin(X) { char __fall = 0; char *__switch_tgt = (char *)(X); switch_begin
#define switch_str_case(X) switch_case (__fall || !strcmp(X, __switch_tgt))
#define switch_str_break __fall = 0; break; }
#define switch_str_fallthrough __fall = 1; }
#define switch_str_default switch_default
#define switch_str_end switch_end; }
#define switch_eq_begin(T, X) { char __fall = 0; T __switch_tgt = X; switch_begin
#define switch_eq_case(X) switch_case (__fall || (X) == __switch_tgt)
#define switch_eq_break __fall = 0; break; }
#define switch_eq_fallthrough __fall = 1; }
#define switch_eq_default switch_default
#define switch_eq_end switch_end; }
#define switch_cmp_begin(C, X) { char __fall = 0; void *__switch_tgt = (void *)(X); int (*__cmp)(const void *, const void *) = C; switch_begin
#define switch_cmp_case(X) switch_case (__fall || !__cmp(X, __switch_tgt))
#define switch_cmp_break __fall = 0; break; }
#define switch_cmp_fallthrough __fall = 1; }
#define switch_cmp_default switch_default
#define switch_cmp_end switch_end; }
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment