Advertisement
Guest User

Fizzbuzz w/o branches or goto (compile with -O2 or higher)

a guest
Nov 30th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef void (*ptr_to_void_fun)(int);
  5.  
  6. ptr_to_void_fun *opts;
  7.  
  8. void next(int i) {
  9.     i++;
  10.     int jmp = ((i % 100 == 0) * 4)
  11.         | (((i % 5 == 0) & (i % 3 == 0)) * 3)
  12.         | (((i % 5 == 0) & (i % 100 != 0) & (i % 3 != 0)) * 2)
  13.         | (((i % 3 == 0) & (i % 5 != 0)) * 1);
  14.     (*(opts[jmp]))(i);
  15. }
  16.  
  17. void fizz(int i) {
  18.     printf("Fizz\n");
  19.     next(i);
  20. }
  21.  
  22. void buzz(int i) {
  23.     printf("Buzz\n");
  24.     next(i);
  25. }
  26.  
  27. void fizzbuzz(int i) {
  28.     printf("FizzBuzz\n");
  29.     next(i);
  30. }
  31.  
  32. void printnum(int i) {
  33.     printf("%i\n", i);
  34.     next(i);
  35. }
  36.  
  37. void null(int i) {
  38.     return;
  39. }
  40.  
  41. int main(int argc, char **argv) {
  42.     opts = malloc(sizeof(ptr_to_void_fun) * 5);
  43.     opts[0] = &printnum;
  44.     opts[1] = &fizz;
  45.     opts[2] = &buzz;
  46.     opts[3] = &fizzbuzz;
  47.     opts[4] = &null;
  48.     next(0);
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement