Skip to content

Instantly share code, notes, and snippets.

@kazuho
Last active February 2, 2020 11:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/b4d810a89f82bbca65aa42cc77954342 to your computer and use it in GitHub Desktop.
Save kazuho/b4d810a89f82bbca65aa42cc77954342 to your computer and use it in GitHub Desktop.
compile-time fizzbuzz that emits optimized code
#include <cstdio>
struct String {
char b[1000];
size_t size;
constexpr String() : b(), size() {}
};
constexpr String operator+(String x, char y) {
x.b[x.size] = y;
x.size = x.size + 1;
return x;
}
constexpr String operator+(String x, const char *y) {
while (*y != '\0')
x = x + *y++;
return x;
}
constexpr String operator+(String x, String y) {
return x + y.b;
}
constexpr String numstr(int n) {
String s;
if (n >= 10)
s = numstr(n / 10);
return s + ('0' + n % 10);
}
constexpr String fizzbuzz(int n) {
String s;
for (int i = 1; i < n; ++i) {
if (i % 15 == 0) {
s = s + "FizzBuzz\n";
} else if (i % 3 == 0) {
s = s + "Fizz\n";
} else if (i % 5 == 0) {
s = s + "Buzz\n";
} else {
s = s + numstr(i) + '\n';
}
}
return s;
}
int main() {
constexpr String b = fizzbuzz(100);
fwrite(b.b, 1, b.size, stdout);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment