• IMPORTANT: Welcome to the re-opening of GameRebels! We are excited to be back and hope everyone has had a great time away. Everyone is welcome!

[C] Generic Fibonacci Macro Implementation

bitm0de

Active Member
Joined
May 24, 2015
Messages
13
Reaction score
0
Code:
#include <stdio.h>

#define def_fib(T) T fib_##T(T x) {  \
  int i;                             \
  T n = 0, m = 1, tmp;               \
  for (i = 0; i < x; ++i)            \
  {                                  \
    n = n + m;                       \
    tmp = n;                         \
    n = m;                           \
    m = tmp;                         \
  }                                  \
  return n;                          \
}

#define fib(T) fib_##T

#define TYPE int
def_fib(TYPE)

int main(void)
{
  TYPE i;
  for (i = 0; i < 10; ++i)
    printf("fib(%d) = %d\n", i, fib(TYPE)(i));
  return 0;
}

Here's some code I just wrote to demonstrate generics in C without having to rewrite code. The example is generating the Fibonacci sequence. This also essentially explains similarly why template specialization in C++ can be convenient but bad for codesize as well if abused, because this is uniquely similar to that of how templates work.. I also wrote this code so that it would be ANSI C (C89) compliant.
 
Top