Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C] Generic Fibonacci Macro Implementation
#1
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.


Forum Jump:


Users browsing this thread: 1 Guest(s)


Powered by © 2002-2020 MyBB Group.
Theme by CreWix. Fixed by Tomik. Customized for Aeowulf.